Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is continue instant?

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"

like image 321
Joel Avatar asked Apr 21 '14 11:04

Joel


2 Answers

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.

like image 148
Mike Seymour Avatar answered Oct 05 '22 18:10

Mike Seymour


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

like image 43
AlexT Avatar answered Oct 05 '22 19:10

AlexT