Joost Cassee wrote:
Hi all,

Just a quick question to set my head right for future Django
contributions. Why is "%s/" % var better than var + '/'? I can think
of some reasons: 1) consistency with other code, 2) certainty of
string concatenation. But is the second expression not much faster?
(This is an honest question, no criticism or anything.)
I'm not sure about speed in this type of trivial case, but I remembered reading about formatting vs. concatenation in Dive into Python[1]. Basically the advantages/disadvantages are as follows:

* concatenation works only with strings and strings. You can't do:

   >>> "Hello. The number of apples I have is: " + 12

But you can do:

   >>> "Hello. The number of apples I have is: %d" % (12,)

If all you are doing is a simple concatenation, I don't see any reason to really worry about the speed, unless you are trying to do megabytes of string concatenation.

If you use string formatting in other places in your code, yes using it for simple concatenations would probably enhance consistency of coding style, but I wouldn't consider it wrong to throw in a concatenation operator.

You got me curious so I wrote a simple loop to concatenate a very small string a million times. I ran it using both methods.

[EMAIL PROTECTED]:~$ time python concattest.py

real    0m0.557s
user    0m0.530s
sys     0m0.022s
[EMAIL PROTECTED]:~$ time python concattest2.py

real    0m0.834s
user    0m0.803s
sys     0m0.024s

concattest.py uses the concatenation operator.
concattest2.py uses string formatting.

I would conclude that for the sake of optimization, it is better to use the concatenation operator for simple cases. I haven't done further testing to see if string formatting ever performs better in certain situations, but for the very simple test case I used, string formatting appears to be slower.

Hopefully this answers your question!

Jeff Anderson

concattest.py:
s1 = "Hello"
i=0
while i<999000:
   greeting="English: " + s1
   i=i+1

concattest2.py:
s1 = "Hello"
i=0
while i<999000:
   greeting="English: %s" % (s1,)
   i=i+1

[1] http://diveintopython.org/native_data_types/formatting_strings.html

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to