1

A quick performance/memory question:

What is better, if there even is a difference?

This

int x;
for (int i = 0; i < 10000; i++)
{
 x = i;
 //do something
}

or this

for (int i = 0; i < 10000; i++)
{
 int x = i;
 //do something
}

?

Karlovsky120
  • 6,212
  • 8
  • 41
  • 94
  • Did you try it? There's almost certainly no difference. – Carl Norum Mar 08 '13 at 00:04
  • @CarlNorum: Primitives, sure. Heavyweight objects? Less so. – Makoto Mar 08 '13 at 00:05
  • If there was a difference, it would be negligible. So prefer the second one, which limits the scope of x. Tune your IO and your algorithms. Micro-optimizations like that won't have any significant impact on performance, but will have one on code readability and robustness. – JB Nizet Mar 08 '13 at 00:05
  • -1 cause you didn't run a simple test on it to find the answer – nathan hayfield Mar 08 '13 at 00:05
  • 5
    @Makoto if you look at the second answer of the link I provided you'll see the byte codes are **exactly** the same - no difference what so ever. – ddmps Mar 08 '13 at 00:06
  • @Makoto as long as the number of created objects is the same, where is defined the reference is also equally fast. – SJuan76 Mar 08 '13 at 00:07
  • compilers nowadays are really good at optimizing code. – aleph_null Mar 08 '13 at 00:07
  • 1
    Any possible difference in efficiency would be so minor that if it matters you probably shouldn't be using Java in the first place. – mkataja Mar 08 '13 at 00:08

2 Answers2

3

I think they will both be the same in terms of assembly (its faster to just do a large stack push than a bunch of push pops for local variables sometimes). It will just reduce the scope of x in the second case even if they both produce the same bytecode.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
  • 1
    How could it produce the same byte code but limit the scope? – Jason Sperske Mar 08 '13 at 00:08
  • Compilers are smart - if they see you don't use it after the loop - they'll limit the scope for you. – ddmps Mar 08 '13 at 00:14
  • @JasonSperske The variable is just an offset in the stack. It limits the scope by forgetting the variable exists outside the loop. – Jesus Ramos Mar 08 '13 at 01:11
  • @JasonSperske In compilers there exists environments and the concept of pushing and popping environments. Inside the loop there exists something which binds to 'x' the stack offset. Outside of it x is unknown because the environment that contained it was popped. – Jesus Ramos Mar 08 '13 at 05:55
3

It is exactly the same... defining a variable (primitive / reference) is just calculating the position where it will live (as an offset of the stack pointer). That is done by the compiler.

SJuan76
  • 24,532
  • 6
  • 47
  • 87