StringBuilder / StringBuffer with literal string in memory [duplicate]
Asked Answered
H

2

7

example code:

StringBuffer sb = new StringBuffer("hi");
sb = null;

Question:

will the literal string "hi" somehow stay in memory, even after the StringBuffer has been garbage collected? Or is it just used to create a char array for the StringBuffer and then never put anywhere in memory?

Hailstorm answered 20/12, 2018 at 21:28 Comment(7)
Prefer StringBuilder to StringBuffer. As for the literal String, it depends on your version of Java and whether or not it's in the intern pool.Impatient
Seems like string literals are put into string pool and remain in memory as long as program is running.Hailstorm
@ElliottFrisch I think you'll have to go back quite some way to find string literals not being interned.Hospodar
@Zeratul Or the class loader collected.Hospodar
@ElliottFrisch There’s no point in preferring StringBuilder over StringBuffer any more. If only used in one thread, the compiler will elide the locking used in StringBuffer, so it won’t make any difference (as a matter of habit, I use StringBuilder too).Mcculley
@OleV.V. well, there’s a difference between waiting for the optimizer to remove an unnecessary operation and not requesting the operation in the first place. So regardless of how tiny the difference might be, due to the absence of any other functional difference, there’s still a reason to prefer StringBuilder. After all, you have to decide for either.Marine
The StringBuffer will copy the argument passed to its constructor, but does not hold any reference to it, hence, whether it gets garbage collected or not, is entirely irrelevant to the life cycle of the "hi" string instance.Marine
E
10

Yes, hi is a compile time constant so it gets interned by the compiler and resides in the string pool.

Moreover G1GC can perform String deduplication as part of JEP 192: String Deduplication in G1 in which case even if hi wasn't interned by javac it might be retained as part of the deduplication.

Extraditable answered 20/12, 2018 at 21:34 Comment(0)
H
4

A string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

JLS 11 > 3. Lexical Structure > 3.10.5. String Literals

Heilbronn answered 20/12, 2018 at 21:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.