<p>Someone told me it's more efficient to use <code>StringBuffer</code> to concatenate strings in Java than to use the <code>+</code> operator for <code>String</code>s. What happens under the hood when you do that? What does <code>StringBuffer</code> do differently?</p>

[{'answer_id': 65677, 'author': 'André Chalella', 'author_id': 4850, 'author_profile': 'https://Stackoverflow.com/users/4850', 'pm_score': 4, 'selected': False, 'text': '<p>One shouldn\'t be faster than the other. This wasn\'t true before Java 1.4.2, because when concatenating more than two strings using the "+" operator, intermediate <code>String</code> objects would be created during the process of building the final string.</p>\n\n<p>However, as the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html" rel="noreferrer">JavaDoc for StringBuffer</a> states, at least since Java 1.4.2 using the "+" operator compiles down to creating a <code>StringBuffer</code> and <code>append()</code>ing the many strings to it. So no difference, apparently.</p>\n\n<p>However, be careful when using adding a string to another inside a loop! For example:</p>\n\n<pre><code>String myString = "";\n\nfor (String s : listOfStrings) {\n  // Be careful! You\'re creating one intermediate String object\n  // for every iteration on the list (this is costly!)\n  myString += s;\n}\n</code></pre>\n\n<p>Keep in mind, however, that usually concatenating a few strings with "+" is cleaner than <code>append()</code>ing them all.</p>\n'}, {'answer_id': 65678, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 3, 'selected': False, 'text': '<p>Under the hood, it actually creates and appends to a StringBuffer, calling toString() on the result.  So it actually doesn\'t matter which you use anymore.</p>\n\n<p>So </p>\n\n<pre><code>String s = "a" + "b" + "c";\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>String s = new StringBuffer().append("a").append("b").append("c").toString();\n</code></pre>\n\n<p>That\'s true for a bunch of inlined appends within a single statement.  If you build your string over the course of multiple statements, then you\'re wasting memory and a StringBuffer or StringBuilder is your better choice.</p>\n'}, {'answer_id': 65680, 'author': 'Ivan Bosnic', 'author_id': 3221, 'author_profile': 'https://Stackoverflow.com/users/3221', 'pm_score': 0, 'selected': False, 'text': '<p>Because Strings are imutable in Java, every time you concanate a String, new object is created in memory. SpringBuffer use the same object in memory.</p>\n'}, {'answer_id': 65684, 'author': 'Loren Segal', 'author_id': 6436, 'author_profile': 'https://Stackoverflow.com/users/6436', 'pm_score': 1, 'selected': False, 'text': '<p>StringBuffer is mutable. It adds the value of the string to the <em>same</em> object without instantiating another object. Doing something like:</p>\n\n<pre><code>myString = myString + "XYZ"\n</code></pre>\n\n<p>will create a <em>new</em> String object.</p>\n'}, {'answer_id': 65717, 'author': 'Alan Krueger', 'author_id': 7708, 'author_profile': 'https://Stackoverflow.com/users/7708', 'pm_score': 2, 'selected': False, 'text': "<p>Java turns string1 + string2 into a StringBuffer construct, append(), and toString().  This makes sense.</p>\n\n<p>However, in Java 1.4 and earlier, it would do this for <em>each</em> + operator in the statement <em>separately</em>.  This meant that doing a + b + c would result in <em>two</em> StringBuffer constructs with <em>two</em> toString() calls.  If you had a long string of concats, it would turn into a real mess.  Doing it yourself meant you could control this and do it properly.</p>\n\n<p>Java 5.0 and above seem to do it more sensibly, so it's less of a problem and is certainly less verbose.</p>\n"}, {'answer_id': 65719, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 1, 'selected': False, 'text': "<p>To concatenate two strings using '+', a new string needs to be allocated with space for both strings, and then the data copied over from both strings.  A StringBuffer is optimized for concatenating, and allocates more space than needed initially.  When you concatenate a new string, in most cases, the characters can simply be copied to the end of the existing string buffer.<br>\nFor concatenating two strings, the '+' operator will probably have less overhead, but as you concatenate more strings, the StringBuffer will come out ahead, using fewer memory allocations, and less copying of data.</p>\n"}, {'answer_id': 65727, 'author': 'Calum', 'author_id': 8434, 'author_profile': 'https://Stackoverflow.com/users/8434', 'pm_score': 6, 'selected': False, 'text': "<p>It's better to use StringBuilder (it's an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here's what happens:</p>\n\n<p>When you use + with two strings, it compiles code like this:</p>\n\n<pre><code>String third = first + second;\n</code></pre>\n\n<p>To something like this:</p>\n\n<pre><code>StringBuilder builder = new StringBuilder( first );\nbuilder.append( second );\nthird = builder.toString();\n</code></pre>\n\n<p>Therefore for just little examples, it usually doesn't make a difference. But when you're building a complex string, you've often got a lot more to deal with than this; for example, you might be using many different appending statements, or a loop like this:</p>\n\n<pre><code>for( String str : strings ) {\n  out += str;\n}\n</code></pre>\n\n<p>In this case, a new <code>StringBuilder</code> instance, and a new <code>String</code> (the new value of <code>out</code> - <code>String</code>s are immutable) is required in each iteration. This is very wasteful. Replacing this with a single <code>StringBuilder</code> means you can just produce a single <code>String</code> and not fill up the heap with <code>String</code>s you don't care about.</p>\n"}, {'answer_id': 65730, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>The StringBuffer class maintains an array of characters to hold the contents of the strings you concatenate, whereas the + method creates a new string each time its called and appends the two parameters (param1 + param2).</p>\n\n<p>The StringBuffer is faster because 1. it might be able to use its already existing array to concat/store all of the strings. 2. even if they don't fit in the array, its faster to allocate a larger backing array then to generate new String objects for each evocation.</p>\n"}, {'answer_id': 65738, 'author': 'slipset', 'author_id': 9422, 'author_profile': 'https://Stackoverflow.com/users/9422', 'pm_score': 3, 'selected': False, 'text': '<p>I think that given jdk1.5 (or greater) and your concatenation is thread-safe you should use StringBuilder instead of StringBuffer\n<a href="http://java4ever.blogspot.com/2007/03/string-vs-stringbuffer-vs-stringbuilder.html" rel="noreferrer">http://java4ever.blogspot.com/2007/03/string-vs-stringbuffer-vs-stringbuilder.html</a>\nAs for the gains in speed:\n<a href="http://www.about280.com/stringtest.html" rel="noreferrer">http://www.about280.com/stringtest.html</a></p>\n\n<p>Personally I\'d code for readability, so unless you find that string concatenation makes your code considerably slower, stay with whichever method makes your code more readable.</p>\n'}, {'answer_id': 65739, 'author': 'Adam Rosenfield', 'author_id': 9530, 'author_profile': 'https://Stackoverflow.com/users/9530', 'pm_score': 1, 'selected': False, 'text': '<p>Because Strings are immutable, each call to the + operator creates a new String object and copies the String data over to the new String.  Since copying a String takes time linear in the length of the String, a sequence of N calls to the + operator results in O(N<sup>2</sup>) running time (quadratic).</p>\n\n<p>Conversely, since a StringBuffer is mutable, it does not need to copy the String every time you perform an Append(), so a sequence of N Append() calls takes O(N) time (linear).  This only makes a significant difference in runtime if you are appending a large number of Strings together.</p>\n'}, {'answer_id': 65744, 'author': 'rgcb', 'author_id': 8178, 'author_profile': 'https://Stackoverflow.com/users/8178', 'pm_score': 0, 'selected': False, 'text': '<p>I think the simplest answer is: it\'s faster.</p>\n\n<p>If you really want to know all the under-the-hood stuff, you could always have a look at the source yourself:</p>\n\n<p><a href="http://www.sun.com/software/opensource/java/getinvolved.jsp" rel="nofollow noreferrer">http://www.sun.com/software/opensource/java/getinvolved.jsp</a></p>\n\n<p><a href="http://download.java.net/jdk6/latest/archive/" rel="nofollow noreferrer">http://download.java.net/jdk6/latest/archive/</a></p>\n'}, {'answer_id': 65753, 'author': 'Christian P.', 'author_id': 9479, 'author_profile': 'https://Stackoverflow.com/users/9479', 'pm_score': 1, 'selected': False, 'text': '<p>As said, the String object is ummutable, meaning once it is created (see below) it cannot be changed.</p>\n\n<blockquote>\n  <p>String x = new String("something"); // or</p>\n  \n  <p>String x = "something";</p>\n</blockquote>\n\n<p>So when you attempt to concanate String objects, the value of those objects are taken and put into a new String object.</p>\n\n<p>If you instead use the StringBuffer, which IS mutable, you continually add the values to an internal list of char (primitives), which can be extended or truncated to fit the value needed. No new objects are created, only new char\'s are created/removed when needed to hold the values.</p>\n'}, {'answer_id': 65770, 'author': 'Benedikt Waldvogel', 'author_id': 4308, 'author_profile': 'https://Stackoverflow.com/users/4308', 'pm_score': 0, 'selected': False, 'text': '<p>The section <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1" rel="nofollow noreferrer">String Concatenation Operator +</a> of the Java Language Specification gives you some more background information on why the + operator can be so slow.</p>\n'}, {'answer_id': 65781, 'author': 'Alexandre Brasil', 'author_id': 8841, 'author_profile': 'https://Stackoverflow.com/users/8841', 'pm_score': 1, 'selected': False, 'text': "<p>When you concatenate two strings, you actually create a third String object in Java. Using StringBuffer (or StringBuilder in Java 5/6), is faster because it uses an internal array of chars to store the string, and when you use one of its add(...) methods, it doesn't create a new String object. Instead, StringBuffer/Buider appends the internal array.</p>\n\n<p>In simple concatenations, it's not really an issue whether you concatenate strings using StringBuffer/Builder or the '+' operator, but when doing a lot of string concatenations, you'll see that using a StringBuffer/Builder is way faster.</p>\n"}, {'answer_id': 65891, 'author': 'tkokoszka', 'author_id': 42201, 'author_profile': 'https://Stackoverflow.com/users/42201', 'pm_score': 5, 'selected': False, 'text': '<p>For simple concatenations like:</p>\n\n<pre><code>String s = "a" + "b" + "c";\n</code></pre>\n\n<p>It is rather pointless to use <code>StringBuffer</code> - as <em>jodonnell</em> pointed out it will be smartly translated into:</p>\n\n<pre><code>String s = new StringBuffer().append("a").append("b").append("c").toString();\n</code></pre>\n\n<p><strong>BUT</strong> it is very unperformant to concatenate strings in a loop, like:</p>\n\n<pre><code>String s = "";\nfor (int i = 0; i &lt; 10; i++) {\n    s = s + Integer.toString(i);\n}\n</code></pre>\n\n<p>Using string in this loop will generate 10 intermediate string objects in memory: "0", "01", "012" and so on. While writing the same using <code>StringBuffer</code> you simply update some internal buffer of <code>StringBuffer</code> and you do not create those intermediate string objects that you do not need:</p>\n\n<pre><code>StringBuffer sb = new StringBuffer();\nfor (int i = 0; i &lt; 10; i++) {\n    sb.append(i);\n}\n</code></pre>\n\n<p>Actually for the example above you should use <code>StringBuilder</code> (introduced in Java 1.5) instead of <code>StringBuffer</code> - <code>StringBuffer</code> is little heavier as all its methods are synchronized.</p>\n'}, {'answer_id': 65893, 'author': 'jb.', 'author_id': 7918, 'author_profile': 'https://Stackoverflow.com/users/7918', 'pm_score': 2, 'selected': False, 'text': '<p>AFAIK it depends on version of JVM, in versions prior to 1.5 using "+" or "+=" actually copied the whole string every time. </p>\n\n<p>Beware that using += actually allocates the new copy of string. </p>\n\n<p>As was pointed using + in loops involves copying. </p>\n\n<p>When strings that are conactenated are compile time constants there concatenated at compile time, so </p>\n\n<pre><code>String foo = "a" + "b" + "c";\n</code></pre>\n\n<p>Has is compiled to:</p>\n\n<pre><code>String foo = "abc"; \n</code></pre>\n'}, {'answer_id': 65964, 'author': 'Brian', 'author_id': 9493, 'author_profile': 'https://Stackoverflow.com/users/9493', 'pm_score': 3, 'selected': False, 'text': '<p>In some cases this is obsolete due to optimisations performed by the compiler, but the general issue is that code like:</p>\n\n<pre><code>string myString="";\nfor(int i=0;i&lt;x;i++)\n{\n    myString += "x";\n}\n</code></pre>\n\n<p>will act as below (each step being the next loop iteration):</p>\n\n<ol>\n<li>construct a string object of length 1, and value "x"</li>\n<li>Create a new string object of size 2, copy the old string "x" into it, add "x" in position 2.</li>\n<li>Create a new string object of size 3, copy the old string "xx" into it, add "x" in position 3.</li>\n<li>... and so on</li>\n</ol>\n\n<p>As you can see, each iteration is having to copy one more character, resulting in us performing 1+2+3+4+5+...+N operations each loop.  This is an O(n^2) operation. If however we knew in advance that we only needed N characters, we could do it in a single allocation, with copy of just N characters from the strings we were using - a mere O(n) operation.</p>\n\n<p>StringBuffer/StringBuilder avoid this because they are mutable, and so do not need to keep copying the same data over and over (so long as there is space to copy into in their internal buffer).  They avoid performing an allocation and copy proportional to the number of appends done by over-allocing their buffer by a proportion of its current size, giving amortized O(1) appending.</p>\n\n<p>However its worth noting that often the compiler will be able to optimise code into StringBuilder style (or better - since it can perform constant folding etc.) automatically.</p>\n'}, {'answer_id': 1156919, 'author': 'Eric Yung', 'author_id': 103340, 'author_profile': 'https://Stackoverflow.com/users/103340', 'pm_score': 2, 'selected': False, 'text': '<p>Further information:</p>\n\n<p>StringBuffer is a thread-safe class</p>\n\n<pre><code>\npublic final class StringBuffer extends AbstractStringBuilder\n    implements Serializable, CharSequence\n{\n// .. skip ..\n     public synchronized StringBuffer append(StringBuffer stringbuffer)\n    {\n        super.append(stringbuffer);\n        return this;\n    }\n// .. skip ..\n}\n</code></pre>\n\n<p>But StringBuilder is not thread-safe, thus it is faster to use StringBuilder if possible</p>\n\n<pre><code>\npublic final class StringBuilder extends AbstractStringBuilder\n    implements Serializable, CharSequence\n{\n// .. skip ..\n    public StringBuilder append(String s)\n    {\n        super.append(s);\n        return this;\n    }\n// .. skip ..\n}\n\n</code></pre>\n'}, {'answer_id': 58792872, 'author': 'Priyantha', 'author_id': 7467246, 'author_profile': 'https://Stackoverflow.com/users/7467246', 'pm_score': 2, 'selected': False, 'text': '<p>The reason is the String immutable. Instead of modifying a string, It creates a new one. \nString pool stores all String values until garbage collectors plush it.\n Think about two strings are there as <code>Hello</code> and <code>how are you</code>. \nIf we consider the String pool, It has two String. </p>\n\n<p><a href="https://i.stack.imgur.com/fRNOG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fRNOG.jpg" alt="enter image description here"></a> </p>\n\n<p>If you try to concatenate these two string as,</p>\n\n<blockquote>\n  <p>string1 = string1+string2</p>\n</blockquote>\n\n<p>Now create a new String object and store it in the String pool.</p>\n\n<p><a href="https://i.stack.imgur.com/NbKGW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NbKGW.jpg" alt="enter image description here"></a></p>\n\n<p>If we try to concatenate thousand of words it\'s getting more memory. The Solution for this is StringBuilder or StringBuffer. It can be created only one Object and can be modified. Because both are mutable.Then no need more memory. If you consider thread-safe then use StringBuffer, Otherwise StringBuilder. </p>\n\n<pre><code>public class StringExample {\n   public static void main(String args[]) {\n      String arr[] = {"private", "default", "protected", "public"};\n      StringBuilder sb= new StringBuilder();\n      for (String value : arr) {\n         sb.append(value).append(" ");\n      }\n      System.out.println(sb);\n   }\n}\n</code></pre>\n\n<blockquote>\n  <p>output : private default protected public</p>\n</blockquote>\n'}]
['https://Stackoverflow.com/questions/65668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']