Created
June 16, 2019 17:19
-
-
Save ukikagi/3a4fabc4d96302288de3ef4a088ad6e9 to your computer and use it in GitHub Desktop.
Performance of string concatenation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
def concat1(N): | |
res = 'a' | |
for _ in [0] * N: | |
res += 'a' | |
def concat2(N): | |
res = 'a' | |
for _ in [0] * N: | |
unused = res | |
res += 'a' | |
nums_iter = [1000, 2000, 5000, 10000, 20000, 50000, 100000] | |
print("concat1") | |
for N in nums_iter: | |
exec_time = min(timeit.repeat('concat1({0})'.format(N), globals=globals(), number=1, repeat=5)) | |
print("N = {0}: exec_time = {1:.6f}".format(N, exec_time)) | |
print() | |
print("concat2") | |
for N in nums_iter: | |
exec_time = min(timeit.repeat('concat2({0})'.format(N), globals=globals(), number=1, repeat=5)) | |
print("N = {0}: exec_time = {1:.6f}".format(N, exec_time)) | |
# concat1 | |
# N = 1000: exec_time = 0.000091 | |
# N = 2000: exec_time = 0.000190 | |
# N = 5000: exec_time = 0.000468 | |
# N = 10000: exec_time = 0.000915 | |
# N = 20000: exec_time = 0.001706 | |
# N = 50000: exec_time = 0.004765 | |
# N = 100000: exec_time = 0.010892 | |
# concat2 | |
# N = 1000: exec_time = 0.000138 | |
# N = 2000: exec_time = 0.000278 | |
# N = 5000: exec_time = 0.000770 | |
# N = 10000: exec_time = 0.001836 | |
# N = 20000: exec_time = 0.006016 | |
# N = 50000: exec_time = 0.043246 | |
# N = 100000: exec_time = 0.165473 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment