I have a case where I'm going through a large amount of data and building up several maps. The result of my function will be Maps
:
case class Maps(map1: Map[String, String], map2: Map[String, String])
I'm trying to decide whether to do this using a functional style, or the "old-fashioned" way of building up mutable maps. The latter would look roughly like
type MutableMap = scala.collection.mutable.Map[String, String]
val MutableMap = scala.collection.mutable.Map
def buildMaps(input: Something): Maps = {
var map1: MutableMap = MutableMap()
var map2: MutableMap = MutableMap()
input.getAnIterator.foreach(x => {
map1 += (key1(x) -> val1(x))
map2 += (key2(x) -> val2(x))
}
Maps(map1.toMap, map2.toMap)
}
The functional alternative that I can see is something like
def addToMaps(maps: Maps, x: SomeElement): Maps =
Maps(maps.map1 + (key1(x) -> val1(x)), maps.map2 + (key2(x) -> val2(x)))
def buildMaps(input: Something): Maps =
input.getAnIterator.foldLeft(Maps(Map(), Map()))(addToMaps)
[My syntax might not be exactly correct, but hopefully this gives the gist of what I'm trying to do.]
The second way seems a lot more "elegant"; but if it's implemented by making repeated copies of immutable maps, it won't be feasible (I expect input
to be quite large).
Is Scala able to optimize the second solution so that its performance is comparable to the first? Is there another approach that I'm missing? Or should I just stick with the non-functional approach?