Temporary variable performance within loop

5
During college a teacher commented to me that declaring a variable before a loop and reusing it was an economical and more interesting way to do it. For example (in Java):

 String str;
 for(Pessoa p : pessoas){
    str = p.getNome();

    //faz algumas operações com str
 }

Working in a programming company I see my experienced co-workers declare inside the loop and claim that it has no difference.

 for(Pessoa p : pessoas){
    String str = p.getNome();

    //faz algumas operações com str
 }

I leave here my doubt, is there any difference in performance or performance between these two forms of temporary variable declaration?

    
asked by anonymous 13.06.2017 / 22:21

1 answer

3

First, are you sure the comparison is this one? Of course assigning a value out of the loop is to be faster. Already declaring should be the same. But not necessarily.

You have to measure. And it needs to measure in several different situations. Even if it makes a difference, I think it will be small.

Note that there may be even different semantics in declaring outside or inside the loop. I do not know how it is in Java. I can search. But I agree with the comment from mgibsonbr, there should be no difference in most situations.

The first creates a variable outside and then assigns new values at each step. In the second the variable is created again and the value is assigned.

Some people will think that creating the variable again will be a cost of memory or processing, but it does not have to happen. It will usually be allocated in my stack location and no processing will be required. So it's supposed to be the same. But I do not guarantee that you have no exceptions in specific circumstances. You'd have to read the spec to see if you do not have a catch.

I would opt for what is the most semantically correct for the case, or if it makes no difference I think it would be declaring inside the loop unless I need performance and a thorough analysis demonstrates that declaring off is better

A tip that is unrelated to the above case: quantitative experience is different from qualitative. I know programmers with 30 years of experience who do everything wrong and do not want to improve. There are teachers who are aware of what they are teaching and others are not. Often the teacher says one thing and the student understands another:)

    
13.06.2017 / 22:37