Skip to content

Instantly share code, notes, and snippets.

@doda-zz
Forked from peterldowns/string_multiply.py
Created November 21, 2012 19:58
Show Gist options
  • Save doda-zz/4127269 to your computer and use it in GitHub Desktop.
Save doda-zz/4127269 to your computer and use it in GitHub Desktop.
Efficient string multiplication in Python
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)
@doda-zz
Copy link
Author

doda-zz commented Nov 21, 2012

cheers @peterldowns

@peterldowns
Copy link

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