Which is faster s + = 'a' or s = s + 'a' in python

s=s+'a'
s+='a'
s.append(a)

      

Is there any difference between the three above?

I am confused by these choices.

What should be used at what time and is string append

faster than others?

-1


source to share


4 answers


Short answer: Nothing. He likes to ask which spoon feeds faster? silver or plastic? Neither he nor the one who uses it.

In other words, it doesn't apply to language. The language simply talks about grammar and semantics, but not about speed, that is, it indicates the ways of expressing something and its grammar, and not how quickly it is done.



Speed ​​is an implementation parameter not a language ; find out the difference. An implementation can refer to s += 'a'

both and s = s + 'a'

similarly below (so there is no difference between the two), but another implementation can implement one faster than the other. So when it comes to speed / efficiency / performance, it is important to specify which version, platform, compiler, etc. Used.

CPython , IronPython , etc. are implementations of the Python language , again their speed when executing such expressions can vary depending on the compiler, platform, etc. Measure, don't speculate!

+3


source


Assuming which 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 don't have a method append()

.

+2


source


You can always run test time and check:

import timeit

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

      

Both give a similar result:

0.000557306000700919
0.0005544929990719538

      

+1


source


  s= s+'a'

  s += 'a'

  s.append(a) 

      

Take a look at http://www.skymind.com/~ocrow/python_string/

s.append (a) is faster among them. Then s must be a string list.

-2


source







All Articles