Which is faster (time complexity) in groovy, .find() or .each()?

Viewed 102

So I'm making a research on which method in groovy makes faster result.

Let's say we have: def storage = [{item:"apple", amount:3, color: "red"}, {item:"mango", amount:5, color: "yellow"}]

Is doing this:

def someMap = [:]
storage.each {
   someMap[it.item] = [amount: it.amount, color: it.color]
}

So when we need to get the amount of an item, we do this: someMap["apple"].amount

Better than doing this? :

def storageFindByItem = { itemName ->
  return storage.find{
    i -> i.item == itemName
  }
} 

So when we need to get the amount of an item, we do this: storageFindByItem("apple").amount

1 Answers

The short answer is that when it comes to performance assessments, you should perform your tests and decide from the results.

With that said, the first option searches an indexed map and would be presumably faster. But this is probably more likely when you're using a HashMap for someMap rather than [:] (LinkedHashMap). And of course this would take an additional amount of memory.
The second option will always be searching linearly whereas finding in a hash map runs in constant time.

All this could be speculation in the face of actual test results, which would really be encouraged.

Related