-
-
Save doda-zz/4127269 to your computer and use it in GitHub Desktop.
Efficient string multiplication in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
test_str = "hello world|" | |
test_times = 1000 | |
def test_str_add(): | |
result = "" | |
for i in xrange(test_times-1): | |
result += test_str | |
return result | |
def test_str_join(): | |
return ''.join(test_str for i in xrange(test_times)) | |
def test_str_nat(): | |
return test_str * test_times | |
def test_str_oth(): | |
return ''.join([test_str] * test_times) | |
print " add: ", timeit.timeit(stmt=test_str_add, number=10000) | |
print " join: ", timeit.timeit(stmt=test_str_join, number=10000) | |
print "native: ", timeit.timeit(stmt=test_str_nat, number=10000) | |
print " other: ", timeit.timeit(stmt=test_str_oth, number=10000) | |
# Moral of the story: Avoid for loops or repeatedly creating new strings (they're immutable) |
Nice addition. Funnily,
''.join([test_str] * test_times)
is much faster than
''.join((test_str,) * test_times)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cheers @peterldowns