<div dir="ltr">While working on #1767933, Serhiy came up with an observation that &quot;monkey-patching&quot; one of the base classes of io is faster than using BytesIO when in need of a file-like object for writing into.<br>

<br>I&#39;ve distilled it into this standalone test:<br><br><div style="margin-left:40px">import io<br><br>data = [b&#39;a&#39;*10, b&#39;bb&#39;*5, b&#39;ccc&#39;*5] * 10000<br><br>def withbytesio():<br>    bio = io.BytesIO()<br>

    for i in data:<br>        bio.write(i)<br>    return bio.getvalue()<br><br>def monkeypatching():<br>    mydata = []<br>    file = io.RawIOBase()<br>    file.writable = lambda: True<br>    file.write = mydata.append<br>

<br>    for i in data:<br>        file.write(i)<br>    return b&#39;&#39;.join(mydata)<br></div><br>The second approach is consistently 10-20% faster than the first one (depending on input) for trunk Python 3.3<br><br>Is there any reason for this to be so? What does BytesIO give us that the second approach does not (I tried adding more methods to the patched RawIOBase to make it more functional, like seekable() and tell(), and it doesn&#39;t affect performance)?<br>

<br>This also raises a &quot;moral&quot; question - should I be using the second approach deep inside the stdlib (ET.tostring) just because it&#39;s faster?<br><br>Eli<br><br></div>