程序运行时背后的逻辑是什么?

What is logic behind runtime of programs?

为什么只是以不同的顺序或风格编写代码,会改变整体运行时间?

例如:

Why is result += "1" is more faster than result = "1" + result ?

更详细的例子:

在为这个 Leetcode 问题编写了一个成功的程序之后 - Add Binary

这里我有 2 个代码片段两者相同,但有非常细微的差别

代码 1

def addBinary(a, b):
    max_len = max(len(a), len(b))
    a = a.zfill(max_len)
    b = b.zfill(max_len)

    result = ""
    carry = 0

    for i in range(len(a)-1, -1, -1):
        x = int(a[i])
        y = int(b[i])

        _sum = x + y + carry

        if _sum == 3:
            result += "1"
            carry = 1
        elif _sum == 2:
            result += "0"
            carry = 1
        elif _sum == 1:
            result += "1"
            carry = 0
        else:
            result += "0"
            carry = 0

    if carry == 1:
        result += "1"

    return result[::-1]

代码 2

def addBinary(a, b):
    max_len = max(len(a), len(b))
    a = a.zfill(max_len)
    b = b.zfill(max_len)

    result = ""
    carry = 0

    for i in range(len(a)-1, -1, -1):
        x = int(a[i])
        y = int(b[i])

        _sum = x + y + carry

        if _sum == 3:
            result = "1" + result
            carry = 1
        elif _sum == 2:
            result = "0" + result
            carry = 1
        elif _sum == 1:
            result = "1" + result
            carry = 0
        else:
            result = "0" + result
            carry = 0

    if carry == 1:
        result += "1"

    return result

CODE 1 的运行时间是 16 msCODE 2 的运行时间是 47 ms。为什么?

在内部优化了向末尾添加字符以在内存中重复使用相同的字符串(字符数组)。在开头添加需要创建一个新的字符串,每个字符的位置移动。