Skip to content

Instantly share code, notes, and snippets.

@arthurschreiber
Created March 11, 2010 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthurschreiber/328956 to your computer and use it in GitHub Desktop.
Save arthurschreiber/328956 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Benchmark for Array#_each</title>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
var Benchmark = {
results: [],
iterations: 1000,
run: function(name, fn) {
var i = 0, start = (new Date).getTime();
for(; i<this.iterations; ++i) {
fn();
}
var end = (new Date).getTime();
this.results.push([name, end - start])
}
};
var array = $R(1, 1000).toArray();
Benchmark.run("default #each", function() {
array.each(Prototype.K);
});
Array.prototype._each = function(iterator) {
for (var i = 0, length = this.length; i < length; iterator(this[i++]));
};
Benchmark.run("#each v1", function() {
array.each(Prototype.K);
});
Array.prototype._each = function(iterator) {
for (var i = 0, item; item = this[i] ; i++)
iterator(item);
};
Benchmark.run("#each v2", function() {
array.each(Prototype.K);
});
Array.prototype._each = function(iterator) {
for (var i = 0, item; item = this[i++];)
iterator(item);
}
Benchmark.run("#each v3", function() {
array.each(Prototype.K);
});
Array.prototype._each = function(iterator) {
for (var i = 0, item; item = this[i++]; iterator(item));
}
Benchmark.run("#each v4", function() {
array.each(Prototype.K);
});
alert(Benchmark.results.inspect());
</script>
</head>
<body>
</body>
</html>
Results: Opera 10.50 Firefox 3.6 Firefox 3.7 Chrome 5.0.342.2 IE 8.0
Default #_each 431ms 733ms 727ms 149ms 1640ms
#_each v1 281ms 720ms 776ms 128ms 1525ms
#_each v2 289ms 714ms 777ms 132ms 1583ms
#_each v3 282ms 724ms 813ms 132ms 1603ms
#_each v4 285ms 720ms 812ms 131ms 1608ms
#_each v1 seems to have the best runtime in Chrome, Opera and IE 8.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment