I have a project where performance is very important. The function I have to check if a list contains an item is being called hundreds of thousand to millions of times per second, and is costing me a lot of time. It is responsible for 60% of the runtime of my program.
Currently, it looks like this:
func byteContains(list[]byte,item byte)bool{
for _,value:=range list{
if value==item{return true}
}
return false
}
This works, but it’s slow. Is there a faster way to do this?
>Solution :
Assuming it is the same list that is being checked or if there are few lists and the lookups are indeed orders of magnitude more frequent than updates, convert the list into a map.
Make the items be the keys and the values some placeholder value like true. Key lookup in maps is O(1), while item lookup in list is O(n).