代码之家  ›  专栏  ›  技术社区  ›  rocksportrocker

Python中的字符串添加真的比使用连接慢吗?

  •  1
  • rocksportrocker  · 技术社区  · 8 年前

    这个问题是指 Is list join really faster than string concatenation in python? https://waymoot.org/home/python_string/

    我想用 + "".join(...) . 但不知怎的,我失败了:

    %%timeit
    result = ""
    for i in range(3000000):
        result = result + 100 * str(i)
    
    3.28 s ± 46.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    

    %%timeit
    result = []
    
    for i in range(3000000):
        result.append(100 * str(i))
    
    result = "".join(result)
    
    4.34 s ± 116 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    

    我正在使用 Python 3.6 我的假设是,最近的版本优化了字符串加法。对此有何评论?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Ignacio Vergara Kausel    8 年前

    问题是你的比较不公平。特别是在第二个代码段中,您还犯了一个错误,即为要连接的字符串的创建计时。附加可能在那里占主导地位。

    首先,我们创建要连接的元素。

    strings = []
    
    for i in range(3000000):
        strings.append(100 * str(i))
    

    时序串串联

    %%timeit
    result = ''
    for i in strings:
       result = result + i
    
    1.65 s ± 23.3 ms per loop
    

    现在计时连接方法

    %timeit result = ''.join(strings)
    
    571 ms ± 10.3 ms per loop
    

    因此,连接比连接更快的说法是正确的!