4

I have worked with String, StringBuilder and StringBuffer in java.
I thought of this question, while I was thinking from efficiency point of view.

Does "+" use in String concatenation affect efficiency?

2
  • 2
    I think this has been discussed a lot here on SO? Commented Aug 3, 2011 at 13:51
  • Yeah, I think that the rule is that you should use stringbuilder if you're concatenating more than two strings... and if you have an idea/answer ahead of time, (1) put it in the question as extra info or (b) don't ask a question to which you already know the answer. Commented Aug 3, 2011 at 13:53

5 Answers 5

6

Yes, but so little it shouldn't matter most of the time.

Using '+' for string constants is the most efficient as the compiler can perform the concatenation.

If you are joining two Strings, the concat method is the most efficient as it avoids using a StringBuilder.

There is almost never a good reason to use StringBuffer except for backward compatibility. StringBuilder or StringWriter are a better choice. However, it is still used explicitly more often than StringBuilder in the JDK :P

StringBuffer is dead, long live StringBuffer

Sign up to request clarification or add additional context in comments.

2 Comments

"so little" in cases of small concatenations. However, I've had experiences dealing with a class with many concatenations (a parser/filter) where simply changing from concatenation to buffer appends halved the (extremely slow) execution time. Microbenchmarks also aren't likely to show you the garbage collection costs of adding all those extra intermediate string objects, but they'll get amortized over the life of your application.
In my applications I use a thread local ByteBuffer and read/write direct from that using methods which don't create any objects. That pretty extreme for 99% of use cases, but it can get your logging down to a few micro-seconds. ;)
4

If you're concatenating in a single statement, then it won't matter since the compiler/JIT compiler will automatically optimize it using a StringBuilder.

So "a"+b+"c" will be optimized to (new StringBuilder("a").append(b).append("c")).toString()

However, if you're concatenating a large number of Strings in a loop, definitely explicitly use a StringBuilder as it will significantly speed up your program.

String a = "";

for( int i = 0; i < 1000000; i++ )
    a += i;

should be changed to

StringBuilder sb = new StringBuilder();

for( int i = 0; i < 1000000; i++ )
    sb.append(i);

String a = sb.toString();

Comments

1

A bit of Yes, But still NO

From the JLS, 15.18.1.2

Optimization of String Concatenation

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

Comments

1

In your example:

" Does +" + " use in String concatenation affect efficiency? "

we have to literal Strings, which might be replaced by the compiler, so this will be faster, than StringBuffer/append/toString.

But efficient/faster compared to what? Code execution? Code writing? Code reading?

Since reading a

"Foo = " + foo;

is very easy, I would recommend it, as long as it isn't repeated a million times, or a " s += s2;" repeated a hundret times.

Especially,

System.out.println ("Player " + n + " scores " + player[n].score); 

is far better readable than

System.out.println (new StringBuffer ("Player ").append ((Integer.valueOf (n)).toString ().append (" scores ").append (...

Just avoid it in applications which need high performance, or concatenate a very large amount of strings, or a large amount recursively.

1 Comment

Well, to be fair, it's really new StringBuffer ("Player ").append(n).append (" scores ").append(player[n].score). But your point is still valid, even though your example is disingenuous.
-2

If you are using multiple times concatenation with '+' , then yes to some extend. Coz when you do String a + String b , it actually internally creates a StringBuffer object and use append() of StringBuffer. So every time you do a '+' a new temporary StringBuffer object gets created initialized with "a" and then appended with "b", which then gets converted to a string object.

So if you need multiple concatenation you should rather create a StringBuffer(thread-safe)/StringBuilder(not thread safe) object and keep appending, so that you avoid the creation of StringBuffer objects again and again.

2 Comments

the "multiple" is only correct of you expand the string in multiple statements. A single statement with + is as efficient as a single stringbuilder but much better to read (and the compiler can better optimize the initial size).
I'm pretty sure the second paragraph addresses this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.