C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Version 1: This loop calls lower() on each iteration. The string is a bit more than 10 characters long.
Version 2: Uses a dictionary lookup on each iteration. If the string is not found, it stores a lowercase version with a normal-case key.
DictionaryPython program that benchmarks lower, dictionary cache
import time
value = "ESSAY ON MAN"
lower_cache = {}
print(time.time())
# Version 1: lowercase the string each iteration.
for i in range(2000000):
res = value.lower()
# Test result.
if res != "essay on man":
print("X")
break
print(time.time())
# Version 2: use a cache in a dictionary to get the lowercase string.
for i in range(2000000):
res = lower_cache.get(value)
# Set in cache if needed.
if res == None:
res = value.lower()
lower_cache[value] = res
# Test result.
if res != "essay on man":
print("X")
break
print(time.time())
Output
1478465952.604
1478465953.01 lower = 0.406 s
1478465953.057 dictionary get = 0.047 s