StringIO
在其代码中有以下注释:
Notes:
- Using a real file is often faster (but less convenient).
- There's also a much faster implementation in C, called cStringIO, but
it's not subclassable.
“真实文件通常更快”这一行对我来说似乎很奇怪:写入磁盘怎么能胜过写入内存?我尝试分析这些不同的案例并得到与这些文档相矛盾的结果,以及这个问题的答案。这另一个问题确实解释了为什么cStringIO在某些情况下会变慢,尽管我在这里没有做任何连接。测试将给定数量的数据写入文件,然后寻找开头并将其读回。在“新”测试中,我每次都创建一个新对象,而在“相同”测试中,我为每次重复截断并重用相同的对象,以排除开销来源。这种开销对于使用具有小数据大小但不是大数据的临时文件很重要。
代码在这里。
Using 1000 passes with size 1.0KiB
New StringIO: 0.0026 0.0025 0.0034
Same StringIO: 0.0026 0.0023 0.0030
New cStringIO: 0.0009 0.0010 0.0008
Same cStringIO: 0.0009 0.0009 0.0009
New tempfile: 0.0679 0.0554 0.0542
Same tempfile: 0.0069 0.0064 0.0070
==============================================================
Using 1000 passes with size 100.0KiB
New StringIO: 0.0093 0.0099 0.0108
Same StringIO: 0.0109 0.0090 0.0086
New cStringIO: 0.0130 0.0139 0.0120
Same cStringIO: 0.0118 0.0115 0.0124
New tempfile: 0.1006 0.0905 0.0899
Same tempfile: 0.0573 0.0526 0.0523
==============================================================
Using 1000 passes with size 1.0MiB
New StringIO: 0.0727 0.0700 0.0717
Same StringIO: 0.0740 0.0735 0.0712
New cStringIO: 0.1484 0.1399 0.1470
Same cStringIO: 0.1493 0.1393 0.1465
New tempfile: 0.6576 0.6750 0.6821
Same tempfile: 0.5951 0.5870 0.5678
==============================================================
Using 1000 passes with size 10.0MiB
New StringIO: 1.0965 1.1129 1.1079
Same StringIO: 1.1206 1.2979 1.1932
New cStringIO: 2.2532 2.2162 2.2482
Same cStringIO: 2.2624 2.2225 2.2377
New tempfile: 6.8350 6.7924 6.8481
Same tempfile: 6.8424 7.8114 7.8404
==============================================================
这两种StringIO
实现相当具有可比性,尽管cStringIO
对于大数据量显着减慢了速度。但是tempfile.TemporaryFile
总是用最慢的3倍StringIO
。