r/ProgrammerHumor • • Jan 16 '14

[deleted by user]

[removed]

1.3k Upvotes

446 comments sorted by

View all comments

Show parent comment

3

u/amoliski Jan 17 '14

...

whoops.

I meant to say to put the String s = ""; outside, and s = ""; inside. Not sure what optimizations exist, but it can't be more expensive than continuously reallocating the memory.

I guess it's a good thing that I'm not paid to do Java at this point.

4

u/8lbIceBag Jan 17 '14

It's really a technicality and not a big deal at all! I was joking. But your way would be ideal on an embedded system. Or even better, a ring buffer. For Java though, I'm not sure how it all works behind the scenes and if one way truly is better than the other.

The reason why it would cause a problem on a low level system is that there isn't garbage collection. It would probably lead to a memory leak due to constantly reallocating the memory. Depends on how the compiler optimizes and such.

1

u/Tmmrn Jan 17 '14

it can't be more expensive than continuously reallocating the memory.

Strings are immutable in java so I would expect it to reallocate memory for each new string anyway.

2

u/StoleAGoodUsername Jan 17 '14

It uses the string pool, so I believe that unless the gc runs mid loop, you are still able to use the same "" in memory from before.

Strings in java are really kinda odd.