Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String multiplication versus for loop

Tags:

python

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 result is -

def string_times(str, n):
    result = ""
    for i in range(n):
       result = result + str
    return result

print string_times('hello',3)

The output is same for both the functions. I am curious how string multiplication (first function) perform against for loop (second function) on performance basis. I mean which one is faster and mostly used?

Also please suggest me a way to get the answer to this question myself (using time.clock() or something like that)

like image 857
Varun Avatar asked Jul 29 '26 17:07

Varun


1 Answers

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.

like image 194
Gareth Latty Avatar answered Aug 01 '26 07:08

Gareth Latty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!