When converting a string (a-> b) in Python, which is faster, if statement or dictionary type?

What I did with the background

I wanted to use GCP's Cloud Functions to convert the input to a pair of words each time, such as "fruit" for "apple" and "vegetable" for "strawberry". I was wondering which is faster, ** converting with if statement ** or ** preparing a dictionary type correspondence table and converting **, so I tried it. Note) In my case, it is often a cold start, so I calculate the required time including dictionary type generation.

Conclusion

** If dictionary reading occurs every time (such as AWS Lambda or GCP Cloud Functions cold start) ** The if statement is faster.

If the key is 5 characters fig2.png

If the key is 10 characters fig1.png (Because I used Colab, the processing speed of each time may not be stable)

** It was an overwhelming victory of the if statement. ** **

If it is not a cold start, I feel that the dictionary type is faster, so I will try it if I feel like it (If document is annoying ...)

environment

Python 3 Google Colaboratory

Verification conditions

-Execute the code to compare ** in the same cell 100 times by changing the number of keys, and compare by the average time required. ・ There are 6 patterns of 5, 10, 25, 50, 100, and 200 keys.

Verification code example

Preparation

import time
import random, string
from statistics import mean

#Random string creation (borrowed from the reference "Generate random strings using Python")
def randomname(n):
   return ''.join(random.choices(string.ascii_letters + string.digits, k=n))

range_ = 5

smp_dict = {}
key_list = []
for i in range(range_):
    key = randomname(10)
    smp_dict[key] = randomname(20)
    key_list.append(key)

#if statement creation
for i in range(range_):
    if i == 0:
        print("      if key == '{}':".format(key_list[i]))
    else :
        print("      elif key == '{}':".format(key_list[i]))
    print("          content = '{}'".format(smp_dict[key_list[i]]))

Create verification code by copying the if statement output above

rnd_key_list = smp_dict.keys()

time_list = []
for i in range(100):
    start = time.time()
    for key in rnd_key_list:
        if key == 's9MT4kkqyg':
            content = 'JpNeK8tDV1FyQfXdzTS0'
        elif key == 'PKFEikSHFM':
            content = 'RxhZqdfsCqLTuxBzIrdV'
        elif key == '04Ex4druSy':
            content = 'GmT0Jx78xPuMrOyVPuik'
        elif key == 'JUJ85l8ayb':
            content = 'xVtzS0HnHHEOHML87z85'
        elif key == 'HnqyHAIcLm':
            content = 'NRNoem9JpGUcFxvccaxD'
    time_list.append(elapsed_time)
if_mean = mean(time_list)
print ("if Mean time:{}".format(if_mean) + "[sec]")


time_list = []
for i in range(100):
    start = time.time()
    Smp_dict = {'s9MT4kkqyg': 'JpNeK8tDV1FyQfXdzTS0', 'PKFEikSHFM': 'RxhZqdfsCqLTuxBzIrdV', '04Ex4druSy': 'GmT0Jx78xPuMrOyVPuik', 'JUJ85l8ayb': 'xVtzS0HnHHEOHML87z85', 'HnqyHAIcLm': 'NRNoem9JpGUcFxvccaxD'}
    for key in rnd_key_list:
        content = Smp_dict[key]
    elapsed_time = time.time() - start
    time_list.append(elapsed_time)
dict_mean = mean(time_list)
print ("dict Mean time:{}".format(dict_mean) + "[sec]")

Explanation of verification code

smp_dict = {}
key_list = []
for i in range(100):
    key = randomname(10)
    smp_dict[key] = randomname(20)
    key_list.append(key)

-> Create a dictionary type & key list with 10 random characters as keys and 20 random characters as values

rnd_key_list = smp_dict.keys()

-> ~~ The order is not preserved when creating a dictionary type ~~, so create a new key list to make the conditions the same. I received a comment from @shiracamus that I will keep it recently!

start = time.time()
Smp_dict = {'BGM85yImoJ': 'i5GozNMNXGdfrlVgmVA0', ...}

-> Read dictionary type after starting measurement

reference

[Python] Measure and display the time required for processing Generate random strings using Python

Recommended Posts

When converting a string (a-> b) in Python, which is faster, if statement or dictionary type?
Timezone specification when converting a string to datetime type in python
Check if the string is a number in python
Hash in Perl is a dictionary in Python
Which is faster, Python shuffle or sample?
python> check NoneType or not> if a == None:> if a is None:
How to use any or all to check if it is in a dictionary (Hash)
Create a dictionary in Python
Why do you add a main ()-if statement in Python?
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
In the python dictionary, if a non-existent key is accessed, initialize it with an arbitrary value
How to make a string into an array or an array into a string in Python
If a beginner learns R or Python this December 2019, which one?
[Introduction to Python] How to output a character string in a Print statement
Delete a particular character in Python if it is the last
Determine if standard output is piped when running a Python script
[Golang] Check if a specific character string is included in the character string
What to do when the value type is ambiguous in Python?
[Python] What is a with statement?
Which is better, PyPy or Python?
[Python] return A [or / and] B
Create a random string in Python
When writing a program in Python
How to input a character string in Python and output it as it is or in the opposite direction.
What to do if there is a decimal in python json .dumps
How to write a string when there are multiple lines in python
When issuing an INSERT statement in Python, no such column is displayed
What happens if you do "import A, B as C" in Python?
What is the fastest way to create a reverse dictionary in python?
Solve ABC175 A, B, C in Python
Precautions when pickling a function in python
Python / dictionary> setdefault ()> Add if not in dictionary
[python] [meta] Is the type of python a type?
Solve ABC165 A, B, D in Python
Generate a class from a string in Python
Output timing is incorrect when standard (error) output is converted to a file in Python
[For beginners] Unexpected behavior if "\" is included when setting the path in Python
Which is better, PyPy or Python?
Analysis by Bayesian inference (2) ... Test cheat discovery algorithm
[Linux] End of process or job, which is better?
Which is better, python standard input receiving input () or sys.stdin?
When converting a string (a-> b) in Python, which is faster, if statement or dictionary type?
[Beginners are worried] Which is better, Ruby, PHP or Python?
[Python] return A [or / and] B
Is the space replaced by a plus sign or% 20 in percent-encoding processing?
Network analysis is a web link structure ①
Network analysis is a web link structure ②
Which is faster, Python shuffle or sample?
How to embed a variable in a python string
converting argument $ 1 type: unsupported type [] string, a slice of string
Get multiple maximum keys in Python dictionary type
Python Note: When assigning a value to a string
python memo-"if not A and B" was "if (not A) and B"
Create a datetime object from a string in Python (Python 3.3)
Put out a shortened URL string in Python
Insert an object inside a string in Python
I checked the reference speed when using python list, dictionary, and set type in.
Get the value of a specific key in a list from the dictionary type in the list with Python
A memo when checking whether the specified key exists in the defined dictionary with python
How to check in Python if one of the elements of a list is in another list
[Python] Precautions when it does not work even if TimedRotatingFileHandler is set in basicConfig in python2