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

前端 未结 4 1523
甜味超标
甜味超标 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:49

    Another approach based on Lennart Regebro approach. This is faster than list method (meth1)

    def meth4(string):
        a = StringIO(string * 100)
        contents = a.getvalue()
        a.close()
        return contents
    
    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())
        print(Timer("meth3(string)", "from __main__ import meth3, string").timeit())
        print(Timer("meth4(string)", "from __main__ import meth4, string").timeit())
    

    Results (sec.):

    meth1 = 7.731315963647944

    meth2 = 9.609279402186985

    meth3 = 0.26534052061106195

    meth4 = 2.915035489152274

提交回复
热议问题