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?