Why does bytearray_obj.extend(bytes) differ from bytearray_obj += bytes?
<p>Just saw (and enjoyed) the video of Brandon Rhodes talking on PyCon 2015 about bytearrays.</p>

<p>He said that <code>.extend</code> method is slow, but <code>+=</code> operation is implemented differently and is much more efficient. Yes, indeed:</p>

<pre><code>&gt;&gt;&gt; timeit.timeit(setup='ba=bytearray()', stmt='ba.extend(b"xyz123")', number=1000000)
0.19515220914036036
&gt;&gt;&gt; timeit.timeit(setup='ba=bytearray()', stmt='ba += b"xyz123"', number=1000000)
0.09053478296846151
</code></pre>

<p>What is the reason of having two ways of extending a bytearray? Are they performing exactly the same task? If not, what is the difference? Which one should be used when?</p>

<blockquote>
  <p>What is the reason of having two ways of extending a bytearray?</p>
</blockquote>

<ul>
<li>An operator is not chainable like function calls, whereas a method is.</li>
<li>The <code>+=</code> operator cannot be used with nonlocal variables.</li>
<li>The <code>+=</code> is slightly faster</li>
<li><code>.extend()</code> may/might/could sometimes possibly be more readable</li>
</ul>

<blockquote>
  <p>Are they performing exactly the same task?</p>
</blockquote>

<p>Depends on how you look at it. The implementation is not the same, but the result usually is. For a bunch of examples and explanations, maybe try the SO search, and for example this question: <a href="http://stackoverflow.com/questions/3653298/concatenating-two-lists-difference-between-and-extend">Concatenating two lists - difference between &#39;+=&#39; and extend()</a></p>

<blockquote>
  <p>Which one should be used when?</p>
</blockquote>

<p>If you care about the small performance difference, use the operator when you can. Other than that, just use whichever you like to look at, of course given the restrictions I mentioned above.</p>

<blockquote>
  <p>But the main question is why += and .extend do not share the same internal function to do the actual work of extending a bytearray.</p>
</blockquote>

<p>Because one is faster but has limitations, so we need the other for the cases where we do have the limitations.</p>

<p><br>
<strong>Bonus</strong>:</p>

<p>The increment operator might cause some funny business with tuples:</p>

<blockquote>
  <p>if you put a list in a tuple and use the += operator to extend the list, the increment succeeds and you get a TypeError</p>
</blockquote>

<p>Source: <a href="https://emptysqua.re/blog/python-increment-is-weird-part-ii/" rel="nofollow">https://emptysqua.re/blog/python-increment-is-weird-part-ii/</a></p>

python