I have a long conditional logic.Wanted to have an efficient way to do so.
(city, country) match {
("USA","NewYork") => someVal=1.0
("USA","SomeOther")=> someVal =2.0
....
}
I have this look-up logic inside of loop, how do I cleanly do it.May be a multi-key map or stategy pattern in Scala
You have some of ways of doing it. Besides the one use used you can try also:
or
Which one is faster? I don't know. You would have to make the benchmarks for your use case.
Mapis probably faster thanmatchbut without benchmarks nobody can tell how much. Which map is faster?map1ormap2? We might guess but without benchmarks for your use cases, it's just guessing.Unfortunately, until you run it in something like JMH and compare the results, it might be just results for cold JVM.
And, as long as you use
Stringas keys, it would be difficult to suggest some solution likeStrategyor anything from GoF, etc, because they rely on either being able to add some property/method to the class to make computation cheaper and/or on the fact that there is finite number of possibilities which unlocks some optimizations.