var MAX = 1000000;
var arr = [], obj = {}, obj2 = {},foo, start;
for(i = 0; i < MAX; i++){
arr.push(i.toString());
}
start = Date.now();
arr.reduce(function(obj2,i){
obj2[i] = true;
return obj2;
},obj2);
console.log('reduce',Date.now() - start);
start = Date.now();
arr.forEach(function(i){
obj[i] = true;
});
console.log('forEach',Date.now() - start);
var MAX = 1000000;
var arr = [], obj = {}, obj2 = {},foo, start;
for(i = 0; i < MAX; i++){
arr.push(i.toString());
}
start = Date.now();
arr.reduce(function(obj2,i){
obj2[i] = true;
return obj2;
},obj2);
console.log('reduce',Date.now() - start);
start = Date.now();
arr.forEach(function(i){
obj[i] = true;
});
console.log('forEach',Date.now() - start);
var MAX = 1000000;
var arr = [], obj = {}, obj2 = {},foo, start;
for(i = 0; i < MAX; i++){
arr.push(i.toString());
}
start = Date.now();
arr.reduce(function(obj2,i){
obj2[i] = true;
return obj2;
},obj2);
console.log('reduce',Date.now() - start);
start = Date.now();
arr.forEach(function(i){
obj[i] = true;
});
console.log('forEach',Date.now() - start);
A quick speed test, comparing forEach and reduce:
var arr = [], obj = {}, obj2 = {}, start;
var MAX = 1000000;
for(i = 0; i < MAX; i++){
arr.push(i.toString());
}
// test reduce
start = Date.now();
arr.reduce(function(obj,i){
obj[i] = true;
return obj;
},obj);
console.log('reduce',Date.now() - start);
// test forEach
start = Date.now();
arr.forEach(function(i){
obj2[i] = true;
});
console.log('forEach',Date.now() - start);
var MAX = 1000000;
var arr = [], obj = {}, obj2 = {},foo, start;
for(i = 0; i < MAX; i++){
arr.push(i.toString());
}
start = Date.now();
arr.reduce(function(obj2,i){
obj2[i] = true;
return obj2;
},obj2);
console.log('reduce',Date.now() - start);
start = Date.now();
arr.forEach(function(i){
obj[i] = true;
});
console.log('forEach',Date.now() - start);
var MAX = 1000000;
var arr = [], obj = {}, obj2 = {},foo, start;
for(i = 0; i < MAX; i++){
arr.push(i.toString());
}
start = Date.now();
arr.reduce(function(obj2,i){
obj2[i] = true;
return obj2;
},obj2);
console.log('reduce',Date.now() - start);
start = Date.now();
arr.forEach(function(i){
obj[i] = true;
});
console.log('forEach',Date.now() - start);
results are:
in node:
in node if you reverse the order:
in firefox:
reversed in firefox:
forEach 2057
reduce 944
If this is for the browser, reduce seems twice as fast in firefox. In node they appear equivalent.
forEach is about as concise as it gets, but hey, one line of code ain't bad. :)