2

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

  • 2
    Clearly the first option is better as far as time complexity goes (and you can improve it by using a hash map instead). But it costs you some extra memory. – ernest_k Sep 08 '20 at 07:23
  • Hi, can you provide an example on how I can be able to improve the 1st option? @ernest_k – Anime Lover Sep 08 '20 at 07:25
  • 2
    I mean use `def someMap = new HashMap<...>()` instead of `def someMap = [:]` – ernest_k Sep 08 '20 at 07:25
  • Alright! If possible, can you give me a quick answer on why hashmap is better? If it's okay with you. – Anime Lover Sep 08 '20 at 07:31
  • "Is A better than B" needs a metric. Then measure for that metric. Assuming you want raw speed, you are best served using a profiler, measure the outcome. In general building a lookup you will use alot will be more efficient. But if your real problem is as "small" as the example you are using, a few linear searches just don't matter. Also for golfing `def storageByItem = storage.collectEntries(new HashMap()) { [it.item, it] }` – cfrick Sep 08 '20 at 08:47

1 Answers1

0

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99