-1

I has simple immutable Map in Scala:

// ... - mean and so on
val myLibrary = Map("qwe" -> 1.2, "qasd" -> -0.59, ...)

And for that myMap i calling MyFind method which call getOrElse(val, 0):

def MyFind (srcMap: Map[String,Int], str: String): Int ={
    srcMap.getOrElse(str,0)
}

val res = MyFind(myLibrary, "qwe")

Problem in that this method called several times for different input strings. E.g. as i suppose for map length 100 and 1 input string it will be try to compare that string 100 times (ones for 1 map value). As you guess for 10,000 it will be gain 10,000 comparisons.

By that with huge map length over 10.000 my method which find value of string keys in that map significantly slows down the work.

What you can advice to speedup that code?

Maybe use another type of Map?

Maybe another collection?

Gudsaf
  • 289
  • 3
  • 12

2 Answers2

3

Map does not have linear time lookup. Default concrete implementation of Map is HashMap

Map is the interface for immutable maps while scala.collection.immutable.HashMap is a concrete implementation.

which has effective constant lookup time, as per collections performance characteristic

                lookup  add  remove  min

HashSet/HashMap  eC     eC    eC     L
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
3

E.g. as i suppose for map length 100 and 1 input string it will be try to compare that string 100 times (ones for 1 map value). As you guess for 10,000 it will be gain 10,000 comparisons.

No, it won't. That's rather the point of Map in the first place. While it allows implementations which do require checking each value one-by-one (such as ListMap) they are very rarely used and by default when calling Map(...) you'll get a HashMap which doesn't. Its lookup is logarithmic time (with a large base), so basically when going from 100 to 10000 it doubles instead of increasing by 100 times.

By that with huge map length over 10.000 my method which find value of string keys in that map significantly slows down the work.

10000 is quite small.

Actually, look at http://www.lihaoyi.com/post/BenchmarkingScalaCollections.html#performance. You can also see that mutable maps are much faster. Note that this predates collection changes in Scala 2.13, so may have changed.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • "collection changes in Scala" - yes, so don not thing that bench of haoyi is truthful for real time... But, thanks for comment. – Gudsaf Feb 16 '20 at 10:40