Suggestion: Add the method isEmpty in the classes StringBuilder and StringBuffer

Hildeberto Mendonça me at hildeberto.com
Mon Feb 11 15:39:00 UTC 2013


On Mon, Feb 11, 2013 at 3:29 PM, Ulf Zibis <Ulf.Zibis at 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.

Thanks for the feedback.

-- 
Hildeberto Mendonça, Ph.D
Blog: http://www.hildeberto.com
Twitter: https://twitter.com/htmfilho <http://www.cejug.org>



More information about the core-libs-dev mailing list