1 min readJun 3, 2018
Compare these two solutions:
map = (fn, [head, …tail]) => {
if (head === undefined) {
return [];
}
return [fn(head), …map(fn, tail)];
};map2 = (fn, arr) => {
let result = [];
for (let i = 0; i < arr.length; i++) {
result[i] = fn(arr[i]);
}
return result;
};let test_data = [];for (let i = 0; i < 5000; i++) {
test_data.push(i);
}let double = (x)=> x * 2;map2(double, test_data);
Map Recursive:
real 0m2.172s
user 0m2.026s
sys 0m0.154s
Map Iterative:
real 0m0.087s
user 0m0.063s
sys 0m0.022s
While the recursive solution is neat, slick, etc — it comes at the cost of a huge performance hit..