Skip to content

Instantly share code, notes, and snippets.

@peterldowns
Created November 21, 2012 02:18
Show Gist options
  • Save peterldowns/4122648 to your computer and use it in GitHub Desktop.
Save peterldowns/4122648 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
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)
# Moral of the story: don't add strings, but feel free to multiply.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment