Pergunta

I have seen most of times developer declares the string in below fashion

Approach 1:-

public void method1(){
String str1 ="Test";

}

Approach 2:-

Per my understanding better approach will be

public void method2(){
String str2 = new String("Test");

}

Again based on my understanding , Second approach is better than first, because String literal are interned and stored in permgen. So it will not be GC'ed even thread comes out of approach 1 but in second approach str2 will be GC'ed(Str 2 will not be interned) as thread comes out of method 2 and GC runs as it is stored in heap not permgen.

Is my understanding correct ?

Per mine understanding I should literal if same string is going to be created again and again as it will be good for performance point of view otherwise go for new String() so that can be GC'ed once not used ?

Linked related string-literal-String-Object

Foi útil?

Solução

In both your examples you have string literal "Test" and in 2) you have another string literal "new". During runtime you create another string with content of "Test" from the string literal "Test" and then create new one containg "Testnew".

In modern Java there is no good reason to use new String(someString);

In older version there was one. String.substring used to create string that was referencing original string and with offset and length restricting it to the vanted value. Therefore if you had long string and created short substring from him, forgot all references to the long one and kept the substring you still had one reference in the substring to the original long string. Therefore the long string would not get GCed. If you used substring = new String(substring), you created separate instance without reference to the original.

Therefore if you target older java platforms, you still should consider using the new String(substring) approach (consider, not just use it!!! You need to identify whether default behavior is problem first).

This change happened between JDK 6 and 7. viz article on programcreek

Licenciado em: CC-BY-SA com atribuição
scroll top