Array is faster than hashmap
for small data access million time.
But what is the catch?
looks take a look.
- hashmap/dictionary is o(1).
{'a':1,'b':2,'c':3}- array/list scale linearly, o(n)
[1,2,3]Hashmap are stored randomly in the RAM.
Array are stored in the bit address side by side. The Jargon is called spatial locality.
Get Darius’s stories in your inbox
Join Medium for free to get updates from this writer.
here is the code I run and the test result
import time
import random
range_val = 100_000 #100_000_0
l = [1, 23, 355, 433, 225]
d = {0: 1, 1: 23, 2: 355, 3: 433, 4: 225} # keys must match randint range (0 to 4)
a = time.time()
for _ in range(range_val):
rand_int = random.randint(0, 4)
l[rand_int]
b = time.time()
c = time.time()
for _ in range(range_val):
rand_int = random.randint(0, 4)
d[rand_int]
dd = time.time()
print("List access time:", b - a)
print("Dict access time:", dd - c)
"""
#at 100_000 range
>>> print("List access time:", b - a)
List access time: 6.365040302276611
>>> print("Dict access time:", dd - c)
Dict access time: 6.720109701156616
>>> print("List access time:", b - a)
List access time: 101.40713310241699
>>> print("Dict access time:", dd - c)
Dict access time: 103.22971367835999
"""
Based on the benchmark, Array is slightly faster than Dict when you access them frequently because the CPU doesn’t have to look at random address (dict) and it can access them sequentially.
As a data professional, you probably worked with lots of mapping table.
country_map = {
"SG": "Singapore",
"MY": "Malaysia",
"TH": "Thailand",
...
}If you have to map table construct in dict, its clean.
status_map = ["Singapore", "Malaysia", "Thailand"]
status = status_map[code] #0,1,2now, if you try to access the list via index, yes its faster. But this because less readable. Down the road in the haystack of codes, you might scratch your head and wonder what does code 0,1,2 stands for.
So performance gain =/ better. Readability is very important as well.
In the end, if the code is easy to maintain, optimisation can come more easily for other area.
#Array #List #Dictionary #Hashmap







