View Single Post
Old 01-06-2013, 01:06 AM   PM User | #23
jmrker
Senior Coder

 
jmrker's Avatar
 
Join Date: Aug 2006
Location: FL
Posts: 2,764
Thanks: 29
Thanked 453 Times in 447 Posts
jmrker will become famous soon enough
Lightbulb

While I agree that the .forEach as defined by 'Old Pedant' has a bunch of potential,
it appears for the simple action I wanted, it is a bit of overkill.

On my machine the following pseudo execution speed test favors the simple function,
just as 'Old Pedant' predicted.
---------------------------------
execution speed test:

.forEach: 425
incrementArray: 16
---------------------------------
Code:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<title> .forEach prototype vs array function </title>
</head>
<body>
<div id="debugger" style="font-family:monospace"></div>

<script type="text/javascript">
Array.prototype.forEach = function( callback ) {
  var ar = [];
  for ( var i = 0; i < this.length; ++i ) { ar[i] = ( callback == null ) ? this[i] : callback( this[i] ); }
  return ar;
}
Array.prototype.createStrArray = function(n) {
  return Object.keys(Object(Array(n)+"r")).map(Number);   // creates [0,1,2,...,(n-1)]
}
function incrementArray(arr) { for (var i=0; i<arr.length; i++) { arr[i]++; } return arr; }

// Execution speed test
var str = 'execution speed test:';
var arr = [].createStrArray(100);

var start1 = new Date();
for (var i=0; i<100000; i++) { var Barr = arr.forEach( function(element) { return element + 1; } ); }
var end1 = new Date();

var start2 = new Date();
for (var i=0; i<100000; i++) { var Barr = incrementArray(arr); }
var end2 = new Date();

str += '<p>.forEach: '+(end1 - start1)+'<br>incrementArray: '+(end2 - start2);

document.getElementById('debugger').innerHTML = str;

</script>
</body>
</html>
jmrker is offline   Reply With Quote