Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Edit:</strong> Moved the parts about immutability to history.</p> <p>Basically, its a question of preallocation. When you use a statement such as </p> <pre><code>sum(["a", "b", "c", ..., ]) </code></pre> <p>and expect it to work similar to a <code>reduce</code> statement, the code generated looks something like</p> <pre><code>v1 = "" + "a" # must allocate v1 and set its size to len("") + len("a") v2 = v1 + "b" # must allocate v2 and set its size to len("a") + len("b") ... res = v10000 + "$" # must allocate res and set its size to len(v9999) + len("$") </code></pre> <p>In each of these steps a new string is created, which for one might give some copying overhead as the strings are getting longer and longer. But that’s maybe not the point here. What’s more important, is that every new string on each line must be <em>allocated</em> to it’s specific size (which. I don’t know it it must allocate in every iteration of the <code>reduce</code> statement, there might be some obvious heuristics to use and Python might allocate a bit more here and there for reuse – but at several points the new string will be large enough that this won’t help anymore and Python must allocate again, which is rather expensive.</p> <p>A dedicated method like <code>join</code>, however has the job to figure out the real size of the string before it starts and would therefore in theory only allocate once, at the beginning and then just fill that new string, which is much cheaper than the other solution.</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