代码之家  ›  专栏  ›  技术社区  ›  Jihan Yin

为什么python中的字符串连接顺序会极大地影响速度?

  •  4
  • Jihan Yin  · 技术社区  · 7 年前

    我刚刚通过调试代码发现了这个问题。我有一个消息列表,作为我试图连接在一起的字符串,我想在每条消息的末尾添加一个新行。

    方法1:

    total_str = ""
    for m in messages:
        total_str = total_str + m + "\n"
    

    这是非常慢的——在大约100000条消息之后,添加每条消息大约需要2-3秒,而在大约300000条消息之后,这个过程基本停止。

    方法2:

    total_str = ""
    for m in messages:
        tmp = m + "\n"
        total_str = total_str + tmp
    

    这种方法在不到一秒钟的时间内就完成了160万条消息的连接。

    我想知道的是,为什么第二种方法比第一种方法快得多?

    3 回复  |  直到 7 年前
        1
  •  3
  •   chepner    7 年前

    a + b + c a b c t = a + b t + c t

    + join

    total_str = "\n".join(messages)
    

    messages

        2
  •  1
  •   ForceBru    7 年前

    a = a + b + c a = (a + b) + c

    • tmp_1 = a + b a
    • a = tmp_1 + c tmp_1

    a = a + tmp

        3
  •  1
  •   Yann Vernier    7 年前

    Python's strings rope data structure total_str = total_str + m + "\n" + left associative total_str str.join io.StringIO StringBuilder writelines

    PyUnicode_Append unicode_modifiable +=