python
Сравнение производительности операций форматирования строк:
import string import timeit def profile(fn): def wrapper(*args, **kwargs): t = timeit.default_timer() r = fn(*args) print(fn.__name__ + ':', round(timeit.default_timer() - t, 4), ' ms') return r return wrapper @profile def check_templates(cnt = 1000): ptn = string.Template('Hi, $name') for i in range(cnt): s = ptn.substitute(name='John') # print(s) @profile def check_format(cnt = 1000): for i in range(cnt): ptn = 'Hi, {}' s = ptn.format('John') # print(s) @profile def check_percent_op(cnt = 1000): for i in range(cnt): ptn = 'Hi, %s' s = ptn%('John') # print(s) @profile def check_f(cnt = 1000): name = 'John' for i in range(cnt): s = f'Hi, {name}' # print(s) @profile def check_concat(cnt = 1000): name = 'John' for i in range(cnt): s = f'Hi, ' + name # print(s) @profile def check_join(cnt = 1000): name = 'John' for i in range(cnt): s = ''.join(('Hi, ', name)) # print(s) def main(cnt=1000): ops = [ check_templates, check_format, check_percent_op, check_join, check_f, check_concat ] for fn in ops: fn(cnt) if __name__ == '__main__': main(10000) # output: # check_templates: 0.1201 ms # check_format: 0.0079 ms # check_percent_op: 0.0053 ms # check_join: 0.0046 ms # check_f: 0.0028 ms # check_concat: 0.0026 ms
(ваш голос учтен)