matter of style and performance question with string cat'ing

Tim Peters tim.one at home.com
Mon May 7 22:28:32 EDT 2001


[Sean 'Shaleh' Perry]
>> I find that I prefer the style:
>>
>> s = '%s is %s' % (foo,bar)
>>
>> as opposed to:
>>
>> s = foo + ' is ' + bar
>>
>> however, which is more efficient?

[Tim]
> Time it, and especially with len(foo) and len(bar) varying over a
> wide range.

>> Usually this does not matter, but I am curious.

> Apparently not enough to call time.clock() <wink>.  Throw in
>
>   ' is '.join((foo, bar))
>
> too, while you're at it.

[Robert Roy]
> You're such a taskmaster. Some timings and some really contrived test
> code.

[and timings showing that ' is '.join() is generally fastest, followed
 by "%s is %s", followed by + +, although the relative order of the
 last two varies by string length]

[and lotsa timing code snipped]

Now time it across platforms.  Also vary the relative lengths of the input
strings (when they're very different, does it matter, e.g., which of foo and
bar is much longer?).  Then repeat all of the above across Python versions
too (hint:  you didn't say which version of Python you used, but the results
give it away).  Then see whether you can guess why I didn't give a "yes"
answer to Sean's "which is more efficient?" <wink>.

some-crap-is-good-for-the-soul-only-the-first-time-you-endure-it-ly y'rs
    - tim





More information about the Python-list mailing list