So according to the optimization tips at http://wiki.python.org/moin/PythonSpeed/PerformanceTips , joining strings should be done with
out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()
and not
out = "<html>" + head + prologue + query + tail + "</html>"
My question is, is this the same for if I wanted to print, instead of store the value? Also, would putting consecutive print statements all on one line be faster? Like would it be better to use
print "Some word"
print "Another line"
print "something else"
or
print '''Some word
Another line
something else'''
Thanks in advance!
String concatenation has been improved for the (fairly common) case where there is only one reference to the string. See PyString_ConcatAndDel in stringobject.c
So usually concatenation in a loop is linear since there is only ever one reference of the string
Here is a simple experiment to demonstrate the behaviour. When there is no room to extend the string the id() changes
>>> s = ""
>>> prev_id = None
>>> for i in range(1000):
... s += "*"
... if prev_id != id(s):
... print id(s), len(s)
... prev_id = id(s)
...
3077352864 1
3077437728 2
3077434328 9
3077428384 17
3077379928 25
3077291808 33
3077712448 41
3077358800 49
3077394728 57
3077667680 65
3077515120 73
3077354176 81
3077576488 89
3077559200 97
3077414248 105
3077670336 113
3077612160 121
3077707040 129
3077526040 137
3077571472 145
3077694944 153
3077595936 161
3077661904 169
3077552608 177
3077715680 185
3077583776 193
3077244304 201
3077604560 209
3077510392 217
3077334304 225
144468768 233
144787416 245
144890104 389
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With