[Python-ideas] Briefer string format

Chris Angelico rosuav at gmail.com
Tue Jul 21 05:47:23 CEST 2015


On Tue, Jul 21, 2015 at 1:35 PM, Tim Peters <tim.peters at gmail.com> wrote:
> [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 ;-)

Interesting that the same optimization can't be done on the .format()
version - it's not as if anyone can monkey-patch str so it does
something different, is it?

To defeat the optimization, I tried this:

rosuav at sikorsky:~$ python3 -mtimeit -s "x=2" "'%d' % 2"
100000000 loops, best of 3: 0.0156 usec per loop
rosuav at sikorsky:~$ python3 -mtimeit -s "x=2" "'%d' % x"
10000000 loops, best of 3: 0.162 usec per loop
rosuav at sikorsky:~$ python3 -mtimeit -s "x=2" "'{}'.format(2)"
1000000 loops, best of 3: 0.225 usec per loop
rosuav at sikorsky:~$ python3 -mtimeit -s "x=2" "'{}'.format(x)"
1000000 loops, best of 3: 0.29 usec per loop

The difference is still there, but it's become a lot less dramatic -
about two to one. I think that's the honest difference between them,
and that's not usually going to be enough to make any sort of
significant difference.

ChrisA


More information about the Python-ideas mailing list