Advertisement
surik00

Python get dict item speeds

Dec 18th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. from timeit import timeit
  2. import random
  3. import string
  4.  
  5. random.choice(string.ascii_lowercase)
  6.  
  7. VALUES_COUNT = 1000
  8.  
  9. values = {}
  10.  
  11.  
  12. def gen_random_str():
  13.     return ''.join(random.choice(string.ascii_letters) for _ in range(random.randint(10, 40)))
  14.  
  15.  
  16. for _ in range(VALUES_COUNT):
  17.     values[gen_random_str()] = 'value'
  18.  
  19.  
  20. existing_key = random.choice(list(values.keys()))
  21. non_existing_key = gen_random_str()
  22. while non_existing_key in values:
  23.     non_existing_key = gen_random_str()
  24.  
  25.  
  26. def use_existing():
  27.     return values[existing_key]
  28.  
  29.  
  30. def with_try_exists():
  31.     try:
  32.         return values[existing_key]
  33.     except KeyError:
  34.         pass
  35.  
  36.  
  37. def with_try_not_exists():
  38.     try:
  39.         return values[non_existing_key]
  40.     except KeyError:
  41.         pass
  42.  
  43.  
  44. def with_in_check_exist():
  45.     if existing_key in values:
  46.         return values[existing_key]
  47.  
  48.  
  49. def with_in_check_not_exist():
  50.     if non_existing_key in values:
  51.         return values[non_existing_key]
  52.  
  53.  
  54. def with_get_exists():
  55.     values.get(existing_key)
  56.  
  57.  
  58. def with_get_not_exists():
  59.     values.get(non_existing_key)
  60.  
  61.  
  62. timeit(use_existing)
  63.  
  64. timeit(with_try_exists)
  65. timeit(with_try_not_exists)
  66.  
  67. timeit(with_in_check_exist)
  68. timeit(with_in_check_not_exist)
  69.  
  70. timeit(with_get_exists)
  71. timeit(with_get_not_exists)
  72.  
  73.  
  74. '''
  75. >>> timeit(use_existing)
  76. 0.09614359300030628
  77. >>>
  78. >>> timeit(with_try_exists)
  79. 0.10425232600027812
  80. >>> timeit(with_try_not_exists)
  81. 0.297110736999457
  82. >>>
  83. >>> timeit(with_in_check_exist)
  84. 0.13227759299843456
  85. >>> timeit(with_in_check_not_exist)
  86. 0.10016654199716868
  87. >>>
  88. >>> timeit(with_get_exists)
  89. 0.1631382230007148
  90. >>> timeit(with_get_not_exists)
  91. 0.1656956420010829
  92. >>>
  93. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement