Strings are also static: creating strings inside methods

I know that during compilation, when created String, this string will be the string used by any objects of this particular signature.

String s = "foo"; <- any other identical lines will be just links to this object.

Is this supported for strings created at runtime at runtime? I have code in which an object contains a piece of string data. The source code is something like

for(datum :data){
    String a = datum.getD();  //getD is not doing anything but returning a field

    StringBuffer toAppend = new StringBuffer(a).append(stuff).toString();

    someData = someObject.getMethod(a);
    //do stuff

}

Since it Stringhas already been created in data, it is better to simply call datum.getD()instead of creating a line at each iteration of the loop.

Is something missing me?

+3
source share
3 answers

String , . a c , b , :

String a = "hello";
String b = hell() + o();
String c = "hell" + "o";

public String hell() {
   return "hell";
}

public String o() {
   return "o";
}

String:

String b = (hell() + o()).intern();

.

+7

 String a = datum.getD();

, datum.getD() a. .

+3

, , . , , , . Class , , , .

, datum.getD(), , .

If you use it datum.getD()several times in a loop, then it makes sense to output the value to a String object, because the cost of creating a string object once may be less than the cost of the call getD()several times.

-2
source

Source: https://habr.com/ru/post/1787482/


All Articles