[Tutor] string formatting

Wayne Werner waynejwerner at gmail.com
Mon Sep 19 20:43:42 CEST 2011


On Mon, Sep 19, 2011 at 1:11 PM, <bodsda at googlemail.com> wrote:

> Is there any additional overhead of using the locals() or format(locals())
> instead of a tuple? - the format option is a double function call so I would
> expect that to be considerably slower
>

Using the following code and timeit, it appears that there is a difference,
but unless you call 0.3-6 ns considerable (assuming I got my math correct:
The difference was ~1.2 or ~1.3 seconds for the classic, ~1.9 for the %
locals version, and timeit runs 1,000,000 times with the default settings),
then the difference isn't terrible.

-Wayne

 from __future__ import print_function
import timeit

def classicwithlocals():
    x = 'hello'
from __future__ import print_function
import timeit

def classicwithlocals():
    x = 'hello'
    y = 'goodbye'
    combined = 'You say %(x)s, and I say %(y)s' % locals()

def classicwithtuple():
    x = 'hello'
    y = 'goodbye'
    combined = 'You say %s, and I say %s' % (x, y)

def withargs():
    x = 'hello'
    y = 'goodbye'
    combined = 'You say {0}, and I say {1}'.format(x, y)


for f in [withargs, classicwithtuple, classicwithlocals]:
        t = timeit.Timer(f)
        print(t.timeit())
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110919/2a034615/attachment.html>


More information about the Tutor mailing list