Permalink
Browse files

Started Collection benchmarks

  • Loading branch information...
1 parent 08ada90 commit dba488d182bb5ec277dffa984ade889e5fe8819d @tj tj committed Dec 14, 2009
Showing with 121 additions and 0 deletions.
  1. +3 −0 Makefile
  2. +83 −0 benchmarks/benchmark.js
  3. +35 −0 benchmarks/collection.js
View
@@ -7,4 +7,7 @@ test:
app:
@$(NODE) examples/app.js
+benchmark:
+ @$(NODE) benchmarks/collection.js
+
.PHONY: test
View
@@ -0,0 +1,83 @@
+
+;(function(){
+ var currentSuite
+
+ /**
+ * Contents of _fn_. Strips function literal and signature.
+ *
+ * @param {function} fn
+ * @return {string}
+ * @api private
+ */
+
+ function contentsOf(fn) {
+ return fn.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]
+ }
+
+ /**
+ * Pad _str_ to _len_.
+ *
+ * @param {string} str
+ * @param {integer} len
+ * @return {string}
+ * @api private
+ */
+
+ function pad(str, len) {
+ return str + (new Array(len - str.length)).join(' ')
+ }
+
+ /**
+ * Time the execution of _fn_
+ *
+ * @param {function} fn
+ * @return {float}
+ * @api private
+ */
+
+ function time(fn) {
+ var start = Number(new Date)
+ fn()
+ return (Number(new Date) - start) / 1000
+ }
+
+ /**
+ * Benchmark _fn_ with the given _label_.
+ *
+ * @param {string} label
+ * @param {function} fn
+ * @api public
+ */
+
+ function benchmark(label, fn) {
+ var duration = time(function(){
+ for (var i = 0; i < currentSuite.times; ++i)
+ fn()
+ }).toFixed(3)
+ print(pad(' ' + label, 50 - duration.toString().length) + duration + ' |')
+ }
+
+ /**
+ * Create a benchmark suite with the given _label_, which
+ * will run each benchmark n _times_. If _times_ is omitted
+ * then it defaults to 1.
+ *
+ * @param {string} label
+ * @param {integer, function} times
+ * @param {function} fn
+ * @api public
+ */
+
+ suite = function(label, times, fn) {
+ currentSuite = this
+ if (typeof times == 'function')
+ this.times = 1, fn = times
+ else
+ this.times = times
+ print('\n ' + pad(label, 42 - this.times.toString().length) + this.times + ' time(s)')
+ print(' -------------------------------------------------')
+ eval(contentsOf(fn))
+ print('')
+ }
+
+})()
View
@@ -0,0 +1,35 @@
+
+require.paths.unshift('lib')
+require.paths.unshift('benchmarks')
+process.mixin(GLOBAL, require('sys'))
+process.mixin(GLOBAL, require('benchmark'))
+require('express')
+
+print = puts
+
+range = function(a, b) {
+ var array = []
+ while (a++ < b)
+ array.push(a-1)
+ return array
+}
+
+suite('Collection with array', 100, function(){
+ array = range(0, 50000)
+
+ benchmark('for', function(){
+ for (var i = 0, len = array.length; i < len; ++i) ;
+ })
+
+ benchmark('for uncached', function(){
+ for (var i = 0; i < array.length; ++i) ;
+ })
+
+ benchmark('forEach', function(){
+ array.forEach(function(){})
+ })
+
+ benchmark('#each', function(){
+ $(array).each(function(){})
+ })
+})

0 comments on commit dba488d

Please sign in to comment.