0

Is there any differences in performance between declaring variables at the beginning of code and declaring them when I need them (outside of readability arguments)?

Suppose I have the following two options:

Option1:

 public void methodA () 
 {
   int  amount;
   long id;
   String name;
   //do something
 }

Option2:

 public void methodB () 
 {
   int  amount;
   //do something 
   long id;
   //do something
   String name;
   //do something
 }

In my opinion, option 2 is more aesthetic and readable and thus is my preference.

Q: But I am just wondering if there exist any differences in performance related to the location of those declarations.

Edit: Thanks to the input of maaartinus, I found that my benchmark examples were wrong (now deleted) and I am looking further into how to write/use benchmark code.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Tony
  • 5,972
  • 2
  • 39
  • 58
  • What is your question about, Java or C++? Be specific to make it an answerable question – Erwin Bolwidt Jul 01 '14 at 03:38
  • The explanation lies in that benchmarking in java is [harder than expected](http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). You're measuring some measuring error. – maaartinus Jul 01 '14 at 07:51
  • @maaartinus Thanks for your links. I am learning. – Tony Jul 01 '14 at 08:09
  • @maaartinus Do you mean the inaccuracy by System.nanoTime() or the Rule 4 (but I can't avoid the effet) – Tony Jul 01 '14 at 10:28
  • No, this inaccuracy is the least problem when the benchmark runs long enough. Follow the link I provided or google out caliper or jmh. – maaartinus Jul 01 '14 at 10:58
  • Sorry for not having read your question more carefully. Basically, there are so many problems... For example, as you don't use any single results, all your computation may be optimized away (google for JMH Blackhole). – maaartinus Jul 01 '14 at 11:12
  • @maaartinus That's all right and thank you for your guideline. – Tony Jul 01 '14 at 11:39

1 Answers1

1

For these cases, I would not expect to see any difference in performance, at least with C++ (though I'd be a little surprised to see a real difference in Java either).

The sort-of exception would be if you moved the definition of a variable inside something like a loop, and it was a type that had significant initialization:

int func() { 
    int amount;
    long id;
    string name;

    while (something) { 
        // ...
    }
    // ...    
}

vs.:

int func() { 
    int amount;
    long id;

    while (something) { 
        string name;
    }
    // ...
}

In the latter case, the string needs to be created and initialized every iteration of the loop, which might well be slower than creating and initializing it once before the loop executes.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111