Skip to content Skip to sidebar Skip to footer

Which Is Faster S+='a' Or S=s+'a' In Python

s=s+'a' s+='a' s.append(a) Is there any difference between above three? I am confused with these choices. Which needs to be used at what time and is string append method faster th

Solution 1:

Short answer: Neither. It's like asking which spoon feeds faster? silver or plastic? Neither, it's up to the person who uses it.

In other words this is inapplicable to a language. A language simply talks about grammar and semantics but not about speed i.e. it specifies ways of expressing something and its grammar, not how fast it is done.

Speed is a parameter of an implementation not language; know the difference. An implementation may treat both s += 'a' and s = s + 'a' similarly underneath (so there's no difference between the two on such an implementation) but another implementation can implement one faster over the other. So when talking about speed/efficiency/performance, it's vital to specify what implementation, platform, compiler, etc. is being used.

CPython, IronPython, etc. are implementations of the Python language, again their speed in performing such expressions may vary based on the compiler, platform, etc. Measure, don't speculate!

Solution 2:

Assuming that s is a string, the time required seems to be identical:

$ python -m timeit 's="x"; s+="x"'
10000000 loops, best of 3: 0.0607 usec per loop
$ python -m timeit 's="x"; s=s+"x"'
10000000 loops, best of 3: 0.0607 usec per loop

Also, string objects to not have an append() method.

Solution 3:

You can always run the test time yourself, and check:

import timeit

print(timeit.timeit("s=''; s+='a'", number=10000))
print(timeit.timeit("s=''; s=s+'a'", number=10000))

Both give similar result:

0.000557306000700919
0.0005544929990719538

Solution 4:

  s= s+'a'

  s += 'a'

  s.append(a) 

Have a look on http://www.skymind.com/~ocrow/python_string/

s.append(a) is faster among these. Then s needs to be a string list.

Post a Comment for "Which Is Faster S+='a' Or S=s+'a' In Python"