Mapreduce optimizations

Backported #2349, thanks @Leperous