什么时候使用StringIO,而不是加入字符串列表? [英] When is StringIO used, as opposed to joining a list of strings?

查看:82
本文介绍了什么时候使用StringIO,而不是加入字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用StringIO作为字符串缓冲区比使用列表作为缓冲区要慢.

Using StringIO as string buffer is slower than using list as buffer.

何时使用StringIO?

When is StringIO used?

from io import StringIO


def meth1(string):
    a = []
    for i in range(100):
        a.append(string)
    return ''.join(a)

def meth2(string):
    a = StringIO()
    for i in range(100):
        a.write(string)
    return a.getvalue()


if __name__ == '__main__':
    from timeit import Timer
    string = "This is test string"
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())

结果:

16.7872819901
18.7160351276

推荐答案

如果测量速度,则应使用cStringIO.

If you measure for speed, you should use cStringIO.

来自文档:

模块cStringIO提供了一个 界面类似于 StringIO模块.大量使用 可以创建StringIO.StringIO对象 通过使用该功能,效率更高 而是来自此模块的StringIO().

The module cStringIO provides an interface similar to that of the StringIO module. Heavy use of StringIO.StringIO objects can be made more efficient by using the function StringIO() from this module instead.

但是StringIO的重点是要成为一个类似文件的对象,因为当有人期望这样并且您不想使用实际文件时.

But the point of StringIO is to be a file-like object, for when something expects such and you don't want to use actual files.

我注意到您使用了from io import StringIO,因此您可能使用的是Python> = 3或至少2.6.单独的StringIO和cStringIO在Py3中消失了.不知道他们用来提供io.StringIO的实现是什么.也有io.BytesIO.

I noticed you use from io import StringIO, so you are probably on Python >= 3 or at least 2.6. The separate StringIO and cStringIO are gone in Py3. Not sure what implementation they used to provide the io.StringIO. There is io.BytesIO too.

这篇关于什么时候使用StringIO,而不是加入字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆