String Multiplication Versus For Loop
I was solving a Python question on CodingBat.com. I wrote following code for a simple problem of printing a string n times- def string_times(str, n): return n * str Official
Solution 1:
We can use the timeit
module to test this:
python -m timeit "100*'string'"1000000 loops, best of 3: 0.222 usec per loop
python -m timeit "''.join(['string' for _ in range(100)])"100000 loops, best of 3: 6.9 usec per loop
python -m timeit "result = ''""for i in range(100):"" result = result + 'string'"100000 loops, best of 3: 13.1 usec per loop
You can see that multiplying is the far faster option. You can take note that while the string concatenation version isn't that bad in CPython, that may not be true in other versions of Python. You should always opt for string multiplication or str.join()
for this reason - not only but speed, but for readability and conciseness.
Solution 2:
I've timed the following three functions:
defstring_times_1(s, n):
return s * n
defstring_times_2(s, n):
result = ""for i inrange(n):
result = result + s
return result
defstring_times_3(s, n):
"".join(s for _ inrange(n))
The results are as follows:
In [4]: %timeit string_times_1('hello', 10)
1000000 loops, best of 3: 262 ns per loop
In [5]: %timeit string_times_2('hello', 10)
1000000 loops, best of 3: 1.63 us per loop
In [6]: %timeit string_times_3('hello', 10)
100000 loops, best of 3: 3.87 us per loop
As you can see, s * n
is not only the clearest and the most concise, it is also the fastest.
Solution 3:
You can use the timeit stuff from either the command line or in code to see how fast some bit of python code is:
$ python -m timeit "\"something\" * 100"
1000000 loops, best of3: 0.608 usec per loop
Do something similar for your other function and compare.
Post a Comment for "String Multiplication Versus For Loop"