Am 11.02.2013 16:39, schrieb Hildeberto Mendonça:
On Mon, Feb 11, 2013 at 3:29 PM, Ulf Zibis <ulf.zi...@cosoco.de 
<mailto:ulf.zi...@cosoco.de>> wrote:

    Am 11.02.2013 12:54, schrieb Hildeberto Mendonça:

        we have a scenario where a project with approximately 500K lines of 
code is
        going through a large refactoring. One of the changes was to replace 
string
        concatenations in loops by StringBuilder.


    Are you aware, that behind the scenes, String concatenations are 
automatically internally
    replaced from javac by StringBuilder invocations, so in the end you might 
have less readable
    code, which is still not faster than before.


Yes, I am. On my understanding the compiler can handle that with concatenations 
like this:

str += "text" + "another" + str2;

but I'm not sure it happens when concatenations are more complex, such as the hypothetical example below:

if(str.isEmpty()) {
   str = "best cars: ";
   boolean firstCar = true;
   for(Car car: cars) {
      if(firstCar) {
         firstCar = false;
      }
      else {
         str += ", ";
      }
      str += car.getName();

      if(car.getBrand() != null) {
         str += " - " + car.getBrand();
      }
   }
   str += ".";
}

I believe, in each iteration, the String is converted to a StringBuilder, appended to, and converted back to a String.

Hi Hildeberto,

maybe your believe is correct.
You could have a look in the byte code by javap.

And additionally you could run a benchmark for both alternatives and compare, if HotSpot compiler would be able to optimize both with same result.

I would like to know the result :-)

-Ulf

Reply via email to