私はグーグルで、これらのバッファモジュールの違いについてもSOを検索しました。しかし、私はまだよく理解していないし、私が読んだいくつかの投稿は時代遅れだと思う。StringIO、cStringIOとByteIOについての混乱
Python 2.7.11では、r = requests.get(url)
を使用して特定の形式のバイナリファイルをダウンロードしました。そして、内容を解析するために設計された関数にStringIO.StringIO(r.content)
,cStringIO.StringIO(r.content)
およびio.BytesIO(r.content)
を渡しました。
これら3つの方法はすべて利用できます。つまり、ファイルがバイナリであっても、StringIO
を使用することはまだ可能です。どうして?
もう1つは効率に関するものです。
In [1]: import StringIO, cStringIO, io
In [2]: from numpy import random
In [3]: x = random.random(1000000)
In [4]: %timeit y = cStringIO.StringIO(x)
1000000 loops, best of 3: 736 ns per loop
In [5]: %timeit y = StringIO.StringIO(x)
1000 loops, best of 3: 283 µs per loop
In [6]: %timeit y = io.BytesIO(x)
1000 loops, best of 3: 1.26 ms per loop
上記のように、cStringIO > StringIO > BytesIO
。
誰かが、io.BytesIO
は、常に新しいコピーを作成して、より多くの時間を費やすことに言及しました。しかし、これはPythonの後のバージョンで修正されたという記事もあります。
だから、誰でも最新のPython 2.xと3.xの両方で、これらの間の完全な比較を行うことができますか。IO
?
私が見つけた参照の一部
:- https://trac.edgewall.org/ticket/12046
io.StringIO requires a unicode string. io.BytesIO requires a bytes string. StringIO.StringIO allows either unicode or bytes string. cStringIO.StringIO requires a string that is encoded as a bytes string.
しかし、任意のエラーをcStringIO.StringIO('abc')
発生しません。
https://review.openstack.org/#/c/286926/1
The StringIO class is the wrong class to use for this, especially considering that subunit v2 is binary and not a string.
http://comments.gmane.org/gmane.comp.python.devel/148717
cStringIO.StringIO(b'data') didn't copy the data while io.BytesIO(b'data') makes a copy (even if the data is not modified later).
-
で、この記事では修正パッチがあります
- SOの投稿の多くはここに記載されていません。ここで
エリックの例2.7、cStringIO.StringIO
とStringIO.StringIO
については
%timeit cStringIO.StringIO(u_data)
1000000 loops, best of 3: 488 ns per loop
%timeit cStringIO.StringIO(b_data)
1000000 loops, best of 3: 448 ns per loop
%timeit StringIO.StringIO(u_data)
1000000 loops, best of 3: 1.15 µs per loop
%timeit StringIO.StringIO(b_data)
1000000 loops, best of 3: 1.19 µs per loop
%timeit io.StringIO(u_data)
1000 loops, best of 3: 304 µs per loop
# %timeit io.StringIO(b_data)
# error
# %timeit io.BytesIO(u_data)
# error
%timeit io.BytesIO(b_data)
10000 loops, best of 3: 77.5 µs per loop
ためのPython 2.7の結果は、はるかに効率的io
よりもされています。
あなたのスニPython 2またはPython 3としてppets? – Eric
@エリック、私はPython 2.7.11ですべてのテストを行った。私は主に2.7を使用しています。「(c)StringIOは、ioで置き換えられています。しかし、私は、他の読者が両方のバージョンについて議論することが意味があると思います。 – Lee
['io'](https://docs.python.org/2/library/io.html)もPython 2にあります – Eric