Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>@Gabe's answer is correct, but needs to be shown clearly rather than hypothesized.</p> <p>CPython (and probably only CPython) does an in-place string append when it can. There are limitations on when it can do this.</p> <p>First, it can't do it for interned strings. That's why you'll never see this if you test with <code>a = "testing"; a = a + "testing"</code>, because assigning a string literal results in an interned string. You have to create the string dynamically, as this code does with <code>str(12345)</code>. (This isn't much of a limitation; once you do an append this way once, the <em>result</em> is an uninterned string, so if you append string literals in a loop this will only happen the first time.)</p> <p>Second, Python 2.x only does this for <code>str</code>, not <code>unicode</code>. Python 3.x does do this for Unicode strings. This is strange: it's a major performance difference--a difference in <em>complexity</em>. This discourages using Unicode strings in 2.x, when they should be encouraging it to help the transition to 3.x.</p> <p>And finally, there can be no other references to the string.</p> <pre><code>&gt;&gt;&gt; a = str(12345) &gt;&gt;&gt; id(a) 3082418720 &gt;&gt;&gt; a += str(67890) &gt;&gt;&gt; id(a) 3082418720 </code></pre> <p>This explains why the non-Unicode version is so much faster in your test than the Unicode version.</p> <p>The actual code for this is <code>string_concatenate</code> in <code>Python/ceval.c</code>, and works for both <code>s1 = s1 + s2</code> and <code>s1 += s2</code>. The function <code>_PyString_Resize</code> in <code>Objects/stringobject.c</code> also says explicitly: <em>The following function breaks the notion that strings are immutable</em>. See also <a href="http://bugs.python.org/issue980695" rel="noreferrer">http://bugs.python.org/issue980695</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload