I am still new to Scala, and one of the things I read about is that for-comprehension is equivalent to a flatMap to a certain extent. However, in my code (below), flatMap is taking at least as twice as long to compute. What could be the reason for this?
This is the slow one:
facts.flatMap(f => factActionsMap(f)).filter(_.isValid(facts))
This is the fast equivalent one:
for {
f <- facts
a <- factActionsMap(f)
if a.isValid(facts)
} yield a
factActionsMap is a map between Fact and a Set[Action].
facts is just a Set[Fact].
Let's check the translation:
So, removing REPL stuff (everything starting with
$) and the implicit parameters, plus reformatting, we get:There are two main differences between this and what you came up with. First,
withFilteris applied tofastActionsMap(f)result, whereas you apply tofacts.flatMapresult. This meansflatMapwill work over all results, instead of just the ones accepted.Second, it uses
withFilterinstead offilter, which avoids creating an extra collection.