Why is ''.join() faster than += in Python?
<p>I'm able to find a bevy of information online (on Stack&nbsp;Overflow and otherwise) about how it's a very inefficient and bad practice to use <code>+</code> or <code>+=</code> for concatenation in Python.</p>

<p>I can't seem to find WHY <code>+=</code> is so inefficient. Outside of a mention <a href="http://stackoverflow.com/a/1350289/3903011" title="What is the most efficient string concatenation method in python?">here</a> that "it's been optimized for 20% improvement in certain cases" (still not clear what those cases are), I can't find any additional information.</p>

<p>What is happening on a more technical level that makes <code>''.join()</code> superior to other Python concatenation methods?</p>

<p>Let's say you have this code to build up a string from three strings:</p>

<pre><code>x = 'foo'
x += 'bar'  # 'foobar'
x += 'baz'  # 'foobarbaz'
</code></pre>

<p>In this case, Python first needs to allocate and create <code>'foobar'</code> before it can allocate and create <code>'foobarbaz'</code>.</p>

<p>So for each <code>+=</code> that gets called, the entire contents of the string and whatever is getting added to it need to be copied into an entirely new memory buffer.  In other words, if you have <code>N</code> strings to be joined, you need to allocate approximately <code>N</code> temporary strings and the first substring gets copied ~N times. The last substring only gets copied once, but on average, each substring gets copied <code>~N/2</code> times.</p>

<p>With <code>.join</code>, Python can play a number of tricks since the intermediate strings do not need to be created. <a href="http://en.wikipedia.org/wiki/CPython">CPython</a> figures out how much memory it needs up front and then allocates a correctly-sized buffer. Finally, it then copies each piece into the new buffer which means that each piece is only copied once.</p>

<hr>

<p>There are other viable approaches which could lead to better performance for <code>+=</code> in some cases. E.g. if the internal string representation is actually a <a href="https://en.wikipedia.org/wiki/Rope_(data_structure)"><code>rope</code></a> or if the runtime is actually smart enough to somehow figure out that the temporary strings are of no use to the program and optimize them away.</p>

<p>However, CPython certainly does <em>not</em> do these optimizations reliably (though it may for a <a href="http://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python/39312172?noredirect=1#comment65960978_39314264">few corner cases</a>) and since it is the most common implementation in use, many best-practices are based on what works well for CPython. Having a standardized set of norms also makes it easier for other implementations to focus their optimization efforts as well.</p>

python optimization