speed diff between set and list
tags: learning diff-between programming
content
task: finding a user in a list
- using
list
def find_user(user, users: List):
for user in users:
if user == target:
return user
return None- using
set
def find_user(user, users: Set):
if user in users:
return user
return None- it’s obvious that
setisO(1)constant time for search- and
listisO(n)linear time for search
- BUT
- in this example, when numbers of
usersis low, searching throughlistis FASTER thanset - because in a
list, objects are right next to each other in memory, looping through elements is FAST - but for
set, elements are usually far from each other due to collision algorithm - Premature Optimization
- in this example, when numbers of