joel
joel

Reputation: 7867

Seq - reverseMap vs reverse.map in Scala

Why is there a method reverseMap on Seq in scala, when it appears to do the same as reverse.map?

Is one perhaps faster than the other?

Upvotes: 0

Views: 531

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369430

For collections which can be efficiently iterated backwards (e.g. doubly-linked lists or indexable collections), reverseMap can potentially be more memory-efficient and time-efficient because reverse is type-preserving. I.e. if it is called on an array, it will create a copy of the array which is reversed, then map that array. (If reverse created reversed iterator instead of an array, things would be different.)

This requires O(n) extra space and iterates the array twice. Whereas reverseMap only iterates once and doesn't need extra space.

Unfortunately, it is not in general possible to leave such optimizations to the compiler. In particular, figuring out that reverse.map and reverseMap are the same is an instance of the Function Problem, which is undecidable.

Upvotes: 3

Related Questions