0

I'm trying to understand the benefits of declaring my String s1 outside of the loop vs inside of the loop (as shown below).

for (int i=0;i<1000;i++)
{
  String s1 = createString(1000);
}

I believe s1 is just referencing the String that was instantiated/allocated as part of createString(), and so it doesn't really cause any additional memory overhead. The memory usage would be the same whether String s1 is declared inside of outside of the loop, as follows:

  • createString() memory allocation = 4 bytes/char * 1000 chars * 1000 times = 4M
  • createString() instantiation of String = 40 bytes/instance * 1000 times = 40K
  • s1 memory allocation = zero.
  • s1 instantiation = zero.

Is there any benefit to declaring the String outside the loop?

  • 1
    I would expect that you'd probably get the same bytecode whether you declare it inside or outside. – Dawood ibn Kareem Mar 16 '14 at 22:18
  • 1
    `char` uses 2 bytes per character. If you have no reason to suspect that where you declare a local variable, I wouldn't worry about it. In short, no, there is no difference. – Peter Lawrey Mar 16 '14 at 22:25
  • In terms of memory there is no difference but check this other questions for other benefits: http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop http://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop – Raul Guiu Mar 16 '14 at 22:28

2 Answers2

0

s1 += createString( ); will allocate 1000x

Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
0

There would be no difference when it comes to memory but in in terms of benefits, you would not be able to reference s1 outside of the for loop.

uesports135
  • 1,083
  • 2
  • 16
  • 25