Comparing blank string definition in Python3

In python3 using

string = ""

or

string = str()

Produces the same result for the programmer. Which one is faster? Using the python module timeit, it’s really easy to find out!

Using string="" is WAY faster.

Here’s the source code for my tests:

from timeit import timeit

durations = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]
definition_techniques = ['s=""', 's=str()']

for definition_technique in definition_techniques:
    print(definition_technique + ' durations')
    for duration in durations:
        print(timeit(definition_technique, number=duration))

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.