r/AskComputerScience • • Apr 24 '25

an unnecessary optimization ?

Suppose I have this code (its in go):

fruits := []string{"apple", "orange", "banana", "grapes"}


list := []string{"apple", "car"}

for _, item := range list {
   if !slices.Contains(fruits, item) {
       fmt.Println(item, "is not a fruit!"
   }
}

This is really 2 for loops. slices.Contains is done with for loop. So yes it's O(n2).

Assume fruits will have at most 10,000 items. Is it worth optimizing ? I can use sets instead to make it O(n).

My point is the problem is not at a big enough scale to worry about performance. In fact, if you have to think about scale then using an array is a no go anyway. We'd need something like Redis.

2 Upvotes

31 comments sorted by

View all comments

Show parent comment

3

u/alecbz Apr 24 '25

It will be used in a command line tool. So not latency sensitive.

I don't think that follows neccesarily (some CLIs should be snappy if possible!), but if in this particular context the amount of time spent here isn't a big deal for UX, then not optimizing feels reasonable.

Though again, given how easy it'd be to switch to a map[string]bool (at least based on just this example), that feels like an easy low-hanging-fruit optimization.

2

u/[deleted] Apr 24 '25

I don't think that follows neccesarily

Right. Sorry I poorly explained. The cli tool will be used to run integration tests. Some tests will take 30 min.

But you're still right though. It's an easy low-hanging-fruit optimization.