javascript - Sum of elements, differences between code -
i have 2 pieces of code both calculating sum of elements of array:
var sum = array.reduce(function(previousvalue, currentvalue) { return previousvalue + currentvalue; }, 0);
or
var sum = 0; array.foreach(function(e) { sum += e; });
are there differences between them beside different implementations? when better use one?
besides personal style preference, there difference in actual performance. 2 perform however.
if you're doing operation lot (or large arrays) consider using third way:
var sum = 0; (l = array.length; l--; ) { sum += array[l]; }
this way faster. check this performance test actual results.
note: gain speed if cache array length. instead of doing this:
for (var = 0; < array.length; i++) {...}
do this:
var l = array.length; (; l--; ) { ... }
or this:
for (l = array.length; l--;) { ... }
Comments
Post a Comment