Skip to content

Instantly share code, notes, and snippets.

@visnup
Created February 27, 2011 10:50
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 visnup/846082 to your computer and use it in GitHub Desktop.
Save visnup/846082 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
String.prototype.count = function(s) {
var n = 0, i = 0;
while ((i = this.indexOf(s, i) + 1) != 0) n++;
return n;
}
function count(str, what) {
var n = 0, i = 0;
while ((i = str.indexOf(what, i) + 1) != 0) n++;
return n;
}
var tasty = "jelly", l = "l";
exports.compare = {
"prototype": function() {
tasty.count(l);
},
"plain": function() {
count(tasty, l);
}
};
require("bench").runMain();
/*
benchmarking count.js
Please be patient.
Scores: (bigger is better)
plain
Raw:
> 1485.5144855144856
> 1457.5424575424574
> 1463.5364635364635
> 1470.5294705294705
> 1416.5834165834167
Average (mean) 1458.741258741259
prototype
Raw:
> 620.3796203796204
> 644.7105788423154
> 643.7125748502993
> 649.3506493506494
> 650.3496503496503
Average (mean) 641.7006147545069
Winner: plain
Compared with next highest (prototype), it's:
56.01% faster
2.27 times as fast
0.36 order(s) of magnitude faster
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment