Speed -- Functions vs "Main"

closed account (jLNv0pDG)
I'm writing some basic programs that are hard on the CPU -- e.g. find all possible moves, prime numbers, etc. I know that you are encouraged to break main out into different functions but I was wondering if this has any negative impact on overall speed.

Basically, will Code 1 run (slightly) faster or at the same speed as Code 2?

1
2
3
4
5
6
7
//CODE 1.cpp
int main()
{
    cout << "hello";
    cout << "goodbye";
    return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//CODE 2.cpp -- calling functions
int main()
{
    hello();
    bye();
    return 0;
}

void hello()
{
    cout << "hello";
}

void bye()
{
    cout << "goodbye";
}


Last edited on
well yes, code 1 should run faster that very very very very very very tiny difference you cant notice.
if you inline the functions and the compiler takes the hint, the two programs would be the same.
Function calls don't have any significant negative impact on performance except when you misuse them.

For example, if you are calculating Fibonacci numbers, using a recursive solution is a Bad Idea because you have to recalculate the (N-1)th number for every Nth number you find, creating an exponential explosion in function calls == work done.

A well-designed algorithm, even one breaking the problem down into many sub-functions, is nearly always superior.

Hope this helps.
Topic archived. No new replies allowed.