Conceptually there is no difference in the results ... flatMap takes a bit more time to get the same result ...
I will show it more practical with an example of flatMap , map , and then flatten and flatten
object Test extends App {
// flatmap
println (timeElapsed (List (List (1, 2, 3, 4), List (5, 6, 7, 8)). flatMap (identity)))
// map and then flatten
println (timeElapsed (List (List (1, 2, 3, 4), List (5, 6, 7, 8)). map (identity) .flatten))
// flatten
println (timeElapsed (List (List (1, 2, 3, 4), List (5, 6, 7, 8)). flatten))
/ **
* timeElapsed
* /
def timeElapsed [T] (block: => T): T = {
val start = System.nanoTime ()
val res = block
val totalTime = System.nanoTime - start
println ("Elapsed time:% 1d nano seconds" .format (totalTime))
res
}
}
Both flatMap and flatten execute with the same result after repeating several times
Conclusion: flatten effective
Elapsed time: 2915949 nano seconds
List (1, 2, 3, 4, 5, 6, 7, 8)
Elapsed time: 1060826 nano seconds
List (1, 2, 3, 4, 5, 6, 7, 8)
Elapsed time: 81172 nano seconds
List (1, 2, 3, 4, 5, 6, 7, 8)