Home > Software engineering >  Is there any speed difference between the following two cases?
Is there any speed difference between the following two cases?

Time:01-25

Will judge_function_2 be faster than judge_function_1? I think judge_function_1's AND statement needs to judge two, while judge_function_2 only needs to be judged once.

#include <iostream>

using namespace std;

bool judge_function_1()
{
    if(100 == 100 || 100 == 200)
    {
        return true;
    }

    return false;
}

bool judge_function_2()
{
    if(100 == 100)
    {
        return true;
    }

    if(100 == 200)
    {
        return true;
    }

    return false;
}

int main()
{
    cout << judge_function_1() << endl;
    cout << judge_function_2() << endl;

    return 0;
}

CodePudding user response:

Using godbolt and compiling with gcc with optimizations enabled results in the following assembly code https://godbolt.org/z/YEfYGv5vh :

judge_function_1():
        mov     eax, 1
        ret
judge_function_2():
        mov     eax, 1
        ret

The functions assembly code is identical and both return true, they will be exactly the same fast.

CodePudding user response:

Compilers know how to read and understand code. They cannot guess your intentions, but thats only an issue when your code does not express your intentions.

A compiler "knows" that 100 == 100 is always true. It cannot be something else.

A compiler "knows" that true || whatever is always true. It cannot be something else.

A compiler "knows" that after a return no other statements are executed in a function.

The transformations are straightforward to proove that both functions are equivalent to

void same_thing_just_with_less_fluff() { return true; }

The code in both functions is just a very complicated way to say return true; / "this function returns true".

Compilers optimize code when you ask them to. If you turn on optimizations there is no reason to expect any difference between the two functions. Calling them has exactly the same effect. There is no observable difference between the two. And as shown above, the way to proove this is rather simple. It is somewhat safe to assume that any compiler can optimize the two functions to simply return true;.


To my experience, a misunderstanding that is common among beginners is that your code would be instructions for your CPU. That when you write 100 == 100 then at runtime there must be 100 in one register and 100 in another register and the cpu needs to carry out an operation to check if the values are the same. This picture is totally wrong.

Your code is an abstract description of the observable behavior of your code. Its a compilers job to translate this abstract description into something your cpu understands and can execute to exhibit the observable behavior you described in your code in accordance with the definitions provided by the C standard.

What your code describes is in plain english: Two functions that both return true.

  • Related