Friday, June 29, 2012

Java Best Practice - Strings Concatenation

1. How to concatenate two Strings inside a loop

Think you need to concatenate strings to an one string, Then probably you chose one of loop in java. But there is a good practice in doing this concatenation which help to increase performance and memory utilization.


Bad  practice

code in line 4 is like

In this syntax it creates a new String object using both previous str object and reStr objects and now str variable is pointed to newly created object. Remember String object is an immutable object hence we can't modify it. Instead of this, we can use StringBuffer to concatenate Strings without creating new objects. see below good practice code segment.

Good practice

here it uses StringBuffer, In initialization it provides first string and inside for loop it append reStr String to that buffer. Therefore this avoid creating immutable string object in each loop. This will help to decrease memory utilization, and increase the performance.

1 comment:

  1. better use StringBuilder. StringBuffer is synchronized (hence slower) and not necessary in most situations.

    ReplyDelete

Sample Text

Website counter

Categories