[Python-ideas] Briefer string format
Tim Peters
tim.peters at gmail.com
Tue Jul 21 05:35:06 CEST 2015
[Alexander Belopolsky]
> One thing I know for a fact is that the use of % formatting instead of
> .format makes a significant difference in my applications. This is not
> surprising given these timings:
>
> $ python3 -mtimeit "'%d' % 2"
> 100000000 loops, best of 3: 0.00966 usec per loop
> $ python3 -mtimeit "'{}'.format(2)"
> 1000000 loops, best of 3: 0.216 usec per loop
Well, be sure to check what you're actually timing. Here under Python 3.4.3:
>>> from dis import dis
>>> def f():
return "%d" % 2
>>> dis(f)
2 0 LOAD_CONST 3 ('2')
3 RETURN_VALUE
That is, the peephole optimizer got rid of "%d" % 2 entirely,
replacing it with the string constant "2". So, in all, it's more
surprising that it takes so long to load a constant ;-)
More information about the Python-ideas
mailing list