'What is logic behind runtime of programs?

Why do just writing the code in different order or style, changes the overall runtime?

For eg:

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

More detailed example:

After writing a successful program for this Leetcode problem - Add Binary

here I have 2 code snippets both SAME, but a very subtle difference.

CODE 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]

CODE 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

The runtime for CODE 1 is 16 ms, and the runtime for CODE 2 is 47 ms. Why?



Solution 1:[1]

Adding characters to the end is optimised internally to reuse the same string (array of characters) in memory. Adding at the beginning requires creating a new string, with the position of each character shifted.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex Hall