Question

In the follow two code snippets, is there actually any different according to the speed of compiling or running?

for (int i = 0; i < 50; i++)
{
    if (i % 3 == 0)
        continue;

    printf("Yay");
}

and

for (int i = 0; i < 50; i++)
{
    if (i % 3 != 0)
        printf("Yay");
}

Personally, in the situations where there is a lot more than a print statement, I've been using the first method as to reduce the amount of indentation for the containing code. Been wondering for a while so found it about time I ask whether it's actually having an effect other than visually.

Reply to Alf (i couldn't get code working in comments...)

More accurate to my usage is something along the lines of a "handleObjectMovement" function which would include

for each object
    if object position is static
        continue

    deal with velocity and jazz

compared with

for each object
    if object position is not static
        deal with velocity and jazz

Hence me not using return. Essentially "if it's not relevant to this iteration, move on"

Was it helpful?

Solution

The behaviour is the same, so the runtime speed should be the same unless the compiler does something stupid (or unless you disable optimisation).

It's impossible to say whether there's a difference in compilation speed, since it depends on the details of how the compiler parses, analyses and translates the two variations.

If speed is important, measure it.

OTHER TIPS

If you know which branch of the condition has higher probability you may use GCC likely/unlikely macro

How about getting rid of the check altogether?

for (int t = 0; t < 33; t++)
{
    int i = t + (t >> 1) + 1;

    printf("%d\n", i);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top