0

I know that StrinbBuilder is good to use, for the connecting two string objects. I am wondering what is happening while doing this:

"a" + i + "b";

Which option is fastest and safest:

1.

int i = 0;
String a = "a" + i + "b";

2.

int i = 0;
String a = "a".concat(String.valueOf(i)).concat("b");

3.

int i = 0;
String a = String.format("a%db", i);
user2618929
  • 1,591
  • 4
  • 13
  • 14

3 Answers3

0

None of them are really optimal for a string concatenation. Do use a StringBuilder, but use it properly, without discarding it each time:

StringBuilder a = new StringBuilder("a");
for(int i = 0;i<10;i++){
    a.append("b");
}

This will perform this without creating new String objects each time.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • Yeah i know about that, but it wasnt the question. I was just asking about connecting Strings during creating first String. What is the fastest way to do this: String a = "a" + i + "b"; – user2618929 Oct 26 '13 at 14:51
  • 1
    `+` operation is in fact the same. so mb `+` is more preferable, cause it's shorter. – DaunnC Oct 26 '13 at 14:59
0

None of them are really good - you're still creating a StringBuilder under the covers and discarding it right after. Here are two other options:

  • Create the StringBuilder explicitly and loop.

    StringBuilder builder = new StringBuilder("a");
    for(int i = 0; i < 10; i++) {
        a.append("b");
    }
    String a = builder.toString();
    
  • Use Guava's Strings.repeat() method, and concatenate the result to a StringBuilder.

    String a = new StringBuilder("a").append(Strings.repeat("b", 9).toString();
    

In terms of performance, there really isn't too much to improve - at some level you're creating n Strings. The only thing we could realistically improve is the memory overhead.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

because strings are immutable in java so every time when you do a string operation that result a new string object, if memory should be considered you must not use string concatenation with "+" sign as it will create multiple string objects and cleanup is not guaranteed as when garbage collector run you dont know, you should also consider that operations should be thread safe so be careful while using stringbuffer and stringbuilder