0

I am analysing a while loop for performance related issues and I'm unsure as to whether a specific line will be causing issues or not. For reference, the code is in java.

    while(blah){
        Class p = new Class(data);
        hash_map.put(key,p);
    }

I've tried to keep it as basic as possible so as to isolate what I'm asking about. The only thing I should maybe mention is that each p created will be different, the data itself is modified in the loop. So the same variable name in each iteration is a placeholder for a different object. My question is whether it would be more efficient on the first iteration to create p (Class p = new Class(data)) and from then on to simply reassign p (so write "p = new Class(data)"). Or is this perhaps the same level of efficiency? I've been trying to get my head around this and if any experienced java people out there could help I'd very much appreciate it, thank you!

  • You're creating a new variable either way it's not going to matter efficiency-wise merely scope-wise. – twain249 Nov 12 '17 at 16:51
  • 2
    Its the same. In both cases memory is allocated for the object and then the pointer is associated to it. – nicovank Nov 12 '17 at 16:52
  • You could simply measure it if you're that concerned but, no, this is not going to make a performance difference. Java is compiled, JITed, optimized, it's not 'making variables' on every loop at runtime. – pvg Nov 12 '17 at 16:55

0 Answers0