Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the fastest way to check if a list contains an item in Go?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading