Loops, function design and efficiency: two questions

I have two related questions: one general and one specific for the project I'm working on.

  • As a rule, if I have a loop with a large number of iterations (millions) with some parts of the code executed under certain conditions, it is better (more efficient) to have one loop with several conditional statements or several loops without them. For instance.

example 1:

while (something())
{
    // some common code
    if (condition_a)
        // some code
    if (condition_b)
        // some code
    // some more common code
}

Example 2:

if (condition_a && condition_b)
{
    while (something())
    {
        // some common and specific code
    }
}
else if (condition_a)
    while (something()) //..
else if (condition_b)
    // Another loop
else //...

Example 2 seems to lead to more efficient code due to redundancy, since conditions are checked only once, not a million times. If the overall code is huge, or there are many possible conditions, this seems extremely redundant.

  • . , . :

    while (reader- > read_point)   {       // -       //   }

, , , . read_point_inside_circle(), read_point_inside_rectangle() ..

, , , , Reader ( , , ).

, , if, , .

for(;;)
{
    if (read_every_point)
        if(!reader->read_point())
            break;
    else if (read_inside_circle)
        if(!reader->read_inside_circle())
            break;
    else if // ...
}
+5
2

, , , , Reader ( , , ).

-, , :

typedef void (Reader::*read_fun_t)();
read_fun_t read_fun = &Reader::read_point;
// or
read_fun_t read_fun = &Reader::read_inside_circle;

...

(reader->*read_fun)();

, , :

void read_point( Reader* reader ){ reader->read_point(); }
void read_inside_circle( Reader* reader ){ reader->read_inside_circle(); }

.

+2

: , , , if/else. , . , .

: , , . , , .

+3

All Articles