[Tutor] Concatenation vs formatting
John Fouhy
john at fouhy.net
Tue Sep 2 02:15:17 CEST 2008
2008/9/1 Richard Lovely <roadierich at googlemail.com>:
> Just a couple of quick questions:
> What differences are there in efficency (i.e. time and memory) between
> string concatenation ("foo" + "bar") and printf style formatting
> ("%s%s" % ("foo","bar")).
The timeit module may provide some insight:
Morpork:~ repton$ python -m timeit '"foo" + "bar"'
10000000 loops, best of 3: 0.0587 usec per loop
Morpork:~ repton$ python -m timeit '"%s%s" % ("foo", "bar")'
1000000 loops, best of 3: 0.474 usec per loop
Morpork:~ repton$ python -m timeit '"".join(["foo", "bar"])'
1000000 loops, best of 3: 0.579 usec per loop
So, from one perspective, using string formatting (for this particular
example) is about 8 times slower. OTOH, from another perspective,
it's less than half a millisecond different. So, like Bob said,
unless you're really doing a whole lot of this, go for whatever makes
for the clearest or most maintainable code.
(and don't forget ''.join if you're doing a lot of concatenation)
--
John.
More information about the Tutor
mailing list