Без лишних слов замеряем скорость конкатенации строк:
def concat_times():
x = 'abc' * 10000
y = 'def' * 10000
time_start = datetime.datetime.now()
z = x + y
print(f'"+" Elapsed: {datetime.datetime.now() - time_start}')
time_start = datetime.datetime.now()
z = "%s%s" % (x, y)
print(f'"%" Elapsed: {datetime.datetime.now() - time_start}')
time_start = datetime.datetime.now()
z = "{}{}".format(x, y)
print('"{}{}" Elapsed:', f'{datetime.datetime.now() - time_start}')
time_start = datetime.datetime.now()
z = "{0}{1}".format(x, y)
print('"{0}{1}" Elapsed:', f'{datetime.datetime.now() - time_start}')
time_start = datetime.datetime.now()
z = f"{x}{y}"
print('"{x}{y}" Elapsed:', f'{datetime.datetime.now() - time_start}')
Результат*:>> concat_times() "+" Elapsed: 0:00:00.000017 "%" Elapsed: 0:00:00.000013 "{}{}" Elapsed: 0:00:00.000019 "{0}{1}" Elapsed: 0:00:00.000012 "{x}{y}" Elapsed: 0:00:00.000008
А теперь списков:
def list_concat_times():
x = [i for i in range(1000)]
y = [i for i in range(1000)]
z = []
time_start = datetime.datetime.now()
z = x + y
print(f'"+" Elapsed: {datetime.datetime.now() - time_start}')
print(f'z len: {len(z)}, x len: {len(x)}, y len: {len(y)}\n')
c = None
time_start = datetime.datetime.now()
c = x.extend(y)
print(f'"extend" Elapsed: {datetime.datetime.now() - time_start}')
print(f'c None, x len: {len(x)}, y len: {len(y)}\n')
x = [i for i in range(1000)]
time_start = datetime.datetime.now()
x.extend(y)
print(f'"extend" Elapsed: {datetime.datetime.now() - time_start}')
print(f'x len: {len(x)}, y len: {len(y)}')
Результат*:"+" Elapsed: 0:00:00.000023 z len: 2000, x len: 1000, y len: 1000 "extend" Elapsed: 0:00:00.000013 c None, x len: 2000, y len: 1000 "extend" Elapsed: 0:00:00.000010 x len: 2000, y len: 1000
*результаты из раза в раз плавают, но в среднем выдерживается полученные.
Комментарии