user1408351 user1408351 - 2 months ago 41
Python Question

python split() vs rsplit() performance?

I have a string in python. I want to split it with

maxsplit = 1
on separator which is pretty close to end of the string.

For e.g.

a = "abcdefghijklmnopqrstuvwxyz,1".


Will
a.split(",", 1)
be better in terms of performance than
a.rsplit(",",1)
?

Answer

Below is a time test using timeit.timeit to compare the speeds of the two methods:

>>> from timeit import timeit
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".split(",", 1)')
1.6438178595324267
>>> timeit('"abcdefghijklmnopqrstuvwxyz,1".rsplit(",", 1)')
1.6466740884665505
>>>

As you can see, they are about equivalent. str.split is a few fractions of a second faster, but that is really unimportant. So, you can pick whichever method you want.

P.S. Although, the str.split method is one less character to type. :)

Comments