snippets/Python-benchmark-different-...

2.9 KiB

different ways to join strings

I measured the time it takes to make 100000 concatenations to the different ways of joining strings to see which is the best and which is the worst

a, b, c = "egg", "ham", "spam"

# Prueba de concatenado con el operador "+"
@explain_time
def test_operator_plus():
    for _ in range(100000):
        a + b + c

>>> test_operator_plus()
         2 function calls in 0.029 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.029    0.029    0.029    0.029 <ipython-input-314-0f5c5594903b>:1(test_operator_plus)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

# Prueba de concatenado con el método "join"
@explain_time
def test_method_join():
    for _ in range(100000):
        "".join((a, b, c))

>>> test_method_join()
         100002 function calls in 0.049 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.032    0.032    0.049    0.049 <ipython-input-316-953c959108ce>:1(test_method_join)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
   100000    0.017    0.000    0.017    0.000 {method 'join' of 'str' objects}

 #Prueba de concatenado con los verbos como en C
@explain_time
def test_format_c_like(): 
    for _ in range(100000):
        "%s%s%s"%(a, b, c) 

>>> test_format_c_like()
         2 function calls in 0.037 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.037    0.037    0.037    0.037 <ipython-input-318-80c622dd1350>:1(test_format_c_like)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

# Prueba de concatenado con el método "format"
@explain_time
def test_method_format():
    for _ in range(100000):
        "{}{}{}".format(a, b, c)

>>> test_method_format()
         100002 function calls in 0.066 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.025    0.025    0.066    0.066 <ipython-input-321-c7b97e43fcc1>:1(test_method_format)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
   100000    0.041    0.000    0.041    0.000 {method 'format' of 'str' objects}

# Prueba de concatenado utilizando los f-strings
@explain_time 
def test_f_strings(): 
    for _ in range(100000):
        f"{a}{b}{c}" 

>>> test_f_strings()
         2 function calls in 0.024 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.024    0.024    0.024    0.024 <ipython-input-324-85e436d5b675>:1(test_f_strings)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}