Why do just writing the code in different order or style, changes the overall runtime?
For eg:
Why is
result += "1"
is more faster thanresult = "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?