3

In my application everything is working fine but I want to increase performance and optimize my code.

which of these two is better for

1.initialisation

String str1=new String("Hello");
String str2="Hello";

2.concatenation

System.out.println(s1 + s2);
System.out.println(new StringBuffer(S1).append(s2));
Shakeeb Ayaz
  • 6,200
  • 6
  • 45
  • 64
  • 1
    Here you have something about strings [link](http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm) – Dariusz Mazur Sep 10 '13 at 09:18
  • @daro2189 thnk for quick reply i'll go through it – Shakeeb Ayaz Sep 10 '13 at 09:19
  • You can take a look at this [post][1] [1]: http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java – Willouz Sep 10 '13 at 09:20
  • What you want to do is called [micro-optimization](http://programmers.stackexchange.com/questions/99445/is-micro-optimisation-important-when-coding). Readable code is better than pseudo-faster code. – Mickäel A. Sep 10 '13 at 09:25
  • 1
    Don't use StringBuffer unless you have to. It was replaced by StringBuilder, nine years ago and was never a good idea in the first place IMHO. http://vanillajava.blogspot.co.uk/2013/04/why-synchronized-stringbuffer-was-never.html – Peter Lawrey Sep 10 '13 at 09:39
  • @daro2189 thnx for helpfull link , it contains lot of info related to my question – Shakeeb Ayaz Sep 10 '13 at 10:07

9 Answers9

6

First of all, do not increase performance and optimize your code, unless you first profiled your application and realized a very good reason to do so.

Second, for initialization of a String variable it is better to not use the String constructor. Using a constant string (as done for str2), Java can pull the String object out of a String pool.

Third, do not use StringBuffer for concatenation. Use StringBuilder instead. StringBuffer's methods are synchronized, which slows down your application significantly. Indeed, your two kinds of concatenation are nearly equal, as all modern compilers create byte code, that uses a StringBuilder for expressions like "s1 + s2".

DrColossos
  • 12,656
  • 3
  • 46
  • 67
Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
  • +1 In most cases, the simplest example was either faster, or just as fast. Writing simpler code has its own benefits such as maintainability which often more important, so stick with simpler, clearer code unless you have measured you need to change something and measured an improvement. – Peter Lawrey Sep 10 '13 at 09:38
1

in initialization Second approach is good as it only creates one object

String str1=new String("Hello");

Here two objects are getting created one in heap and other one in String pool

String str2="Hello";

here only one object is getting created in String pool.

System.out.println(s1 + s2);

Here total three objects are there s1 s2 and s1+s2 all in String pool

System.out.println(new StringBuffer(S1).append(s2));

Here only one object in head area which is S1+S2 so in both cases second approach is good

ankit
  • 4,919
  • 7
  • 38
  • 63
1

For the initialization it is better the second approach :

String str2="Hello";

because in this way you can make use of the Java String Pool and avoid not needed allocations .

For concatenation the second approach would be the best bet when you have to perform a lot of string concatenation, to concatenate only two string, the first approach is simpler and enough...

aleroot
  • 71,077
  • 30
  • 176
  • 213
  • I'd like to add that StringBuilder is faster than StringBuffer (it's not synchronized). –  Sep 10 '13 at 09:21
1

Use

String str2="Hello";

for string initialization, because if "Hello" string is avaialable in JVM string pool then new memory object will not be created

Two other suggestions:

  1. If you are manipulating string then use StringBuffer as it does not create new strings with each string manipulation as String class does.
  2. If your application is thread safe then use StringBuilder to avoid unnecessary overhead of StringBuffer, which is designed for multi-threaded operations.
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

For initialization it is better to use the second version because that will enable the JVM the String "interned", that means it can always return the same String-instance every time that constant is used. The first version will always create a new String object when this code is encountered, thus creating extra memory-consumption.

For concatenation, in simple cases like your example the compiler will do optimization so both ways will end up essentially the same. For more complicated String-concatenations it is better to either use a Stringbuffer or a StringBuilder. Use of a StringBuffer is necessary when the StringBuilder is accessed from multiple threads, in other cases StringBuilder will give better performance because it won't do any locking.

piet.t
  • 11,718
  • 21
  • 43
  • 52
1
System.out.println(s1 + s2);
System.out.println(new StringBuffer(S1).append(s2));
  1. From those two above, first would be faster, because + is translated into StringBuilder, that is faster compared to StringBuffer

  2. And anyway... fastest, but some kind nasty-looking, way of adding 2 Strings is to use string1.concat(string2) method, that does not need to produce new object of Stringbuilder of Buffer.

  3. You can also reuse the same StringBuilder for adding many Strings, by reseting it with sb.setLength(0) after each fully-added-String

:

StringBuilder sb = new StringBuilder();
String done1 = sb.append("1").append("2").append("3").toString();
sb.setLength(0);
String done2 = sb.append("4").append("5").append("6").toString();
sb.setLength(0);
String done3 = sb.append("7").append("8").append("9").toString();
sb.setLength(0);
System.out.println(done1);
System.out.println(done2);
System.out.println(done3);

Lastly, inside loops, you should always use StringBuilder/Buffer explicitly, ignoring that magic about using +. Because you would end up with many temporally StringBuilder objects, instead of only one that you should explicitly create before loop.

    //not:
    String result = "";
    for (int i = 0; i < 20; i++) {
        result += i; // this would create new StringBuilding in bytecode
    }
    System.out.println(result);

    //but:
    StringBuilder result1 = new StringBuilder();
    for (int i = 0; i < 20; i++) {
        result1.append(i);
    }
    System.out.println(result1);
Community
  • 1
  • 1
dantuch
  • 9,123
  • 6
  • 45
  • 68
1

In initialization

 String str2="Hello";

is better approach

In concatenation

System.out.println(s1 + s2);

is better approach.

Beacuse both they use String Constant pool which is ment for performance improvement

Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
0

1)Go for literals,String literals are stored in a common pool. This facilitates sharing of storage for strings with the same contents to conserve storage. String objects allocated via new operator are stored in the heap, and there is no sharing of storage for the same contents.

other than

Literals are reader friendly ,than using constructors.

2)Go for StringBuilder instead of + which avoid's multiple string object creations.

For the second point ,with 2 to 3 appends or +'s ,there is no much difference.But when you are appending a 50 strings to one another,It matters'.

Might helpful :

Most of the memory related issues maintains/resolves by java itself.I belive in clean and readable code unless it's showing major impact.

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Don't optimize before you REALLY need this.

If you optimize when it is not needed you decrease readability and waste time. It is really rare case that string initialization will cause performance problems for you.

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63