0

Is there any performance difference between:

uint a;
for (uint i = 0 ; i < n ; ++i)
{
    a = i;
}

and:

for (uint i = 0 ; i < n ; ++i)
{
    uint a;
    a = i;
}

Does the second piece of code result in a program creating a variable (allocating memory or sth) multiple times instead of just once? If not, is it because both codes are equivalent or because of some compiler optimization?

NPS
  • 6,003
  • 11
  • 53
  • 90

3 Answers3

3

I expect all modern compilers to produce identical code in both cases.

You might be surprised to know that with most compilers there is absolutely no difference whatsoever in the amount of overhead between either case.

In brief, these kinds of variables are instantiated on the stack, and a compiler, for each function, computes the maximum amount of stack needed to instantiate all local variables inside the function, and allocate the required stack space at the function's entry point.

Of course, if instead of a simple int you have some class with a non-trivial amount of complexity in its constructor, then it would certainly make a lot of difference, in several ways. But for a simple int like this, absolutely nothing.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
2

Assuming uint is a basic data type, I would say they are the same. Apart from the fact you can use a after the loop in the first example, of course. This is because the cost of placing basic data-types on the stack is trivial and the compiler can optimize this case so the memory is actually reserved once, as if you had declared it outside the loop.

If uint is a class, placing it outside the loop and reusing it could be faster. For example, declaring a std::string before a loop and reusing it inside the loop can be faster than creating a new string each iteration. This is because a string can reuse its existing dynamic memory allocation.

You can look at the disassembly of your compiler to see if there is any difference.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
0

The second example must be slightly slower because a is being redefined for each iteration. This means that space is being set aside to store the maximum possible value of a (in this case, probably 4 bytes of memory). The allocation of that space is a command which will be executed, so I think that it is slower. Does it matter? Probably not.

  • 2
    "must" is wrong. It could be exactly the same. Also, int could be more than 2 bytes (it commonly is) – Neil Kirk Oct 01 '14 at 01:01
  • 1
    Additionally, the amount of effort needed to bind an int, whether its two or four bytes, on the stack, at every entry point in the loop, is exactly 0 CPU cycles, with any sane compiler. – Sam Varshavchik Oct 01 '14 at 01:04
  • @NeilKirk I improved my diction and corrected the part about uint being 2 bytes... I was thinking of a ushort. As to the last comment, Whether completely negligible or not, it still affects the speed. –  Oct 01 '14 at 01:05