When is StringIO used, as opposed to joining a list of strings?

前端 未结 4 1486
甜味超标
甜味超标 2021-01-30 15:56

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

When is StringIO used?

from io import StringIO


def meth1(string):
    a = []
             


        
4条回答
  •  心在旅途
    2021-01-30 16:36

    Well, I don't know if I would like to call that using it as a "buffer", you are just multiplying a string a 100 times, in two complicated ways. Here is an uncomplicated way:

    def meth3(string):
        return string * 100
    

    If we add that to your test:

    if __name__ == '__main__':
    
        from timeit import Timer
        string = "This is test string"
        # Make sure it all does the same:
        assert(meth1(string) == meth3(string))
        assert(meth2(string) == meth3(string))
        print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
        print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())
        print(Timer("meth3(string)", "from __main__ import meth3, string").timeit())
    

    It turns out to be way faster as a bonus:

    21.0300650597
    22.4869811535
    0.811429977417
    

    If you want to create a bunch of strings, and then join them, meth1() is the correct way. There is no point in writing it to StringIO, which is something completely different, namely a string with a file-like stream interface.

提交回复
热议问题