Python equivalent of Java StringBuffer?

后端 未结 8 1305
半阙折子戏
半阙折子戏 2020-12-04 21:10

Is there anything in Python like Java\'s StringBuffer? Since strings are immutable in Python too, editing them in loops would be inefficient.

8条回答
  •  日久生厌
    2020-12-04 21:14

    Just a test I run on python 3.6.2 showing that "join" still win BIG!

    from time import time
    
    
    def _with_format(i):
        _st = ''
        for i in range(0, i):
            _st = "{}{}".format(_st, "0")
        return _st
    
    
    def _with_s(i):
        _st = ''
        for i in range(0, i):
            _st = "%s%s" % (_st, "0")
        return _st
    
    
    def _with_list(i):
        l = []
        for i in range(0, i):
            l.append("0")
        return "".join(l)
    
    
    def _count_time(name, i, func):
        start = time()
        r = func(i)
        total = time() - start
        print("%s done in %ss" % (name, total))
        return r
    
    iterationCount = 1000000
    
    r1 = _count_time("with format", iterationCount, _with_format)
    r2 = _count_time("with s", iterationCount, _with_s)
    r3 = _count_time("with list and join", iterationCount, _with_list)
    
    if r1 != r2 or r2 != r3:
        print("Not all results are the same!")
    

    And the output was:

    with format done in 17.991968870162964s
    with s done in 18.36879801750183s
    with list and join done in 0.12142801284790039s
    

提交回复
热议问题