diff --git a/proto.js b/proto.js index 8163808..8873433 100644 --- a/proto.js +++ b/proto.js @@ -5,10 +5,19 @@ function Single (async, opts) { if(!(this instanceof Single)) return new Single(async, opts) this.writing = false this.value = null + this._next = 0 this.onDrain = null this._async = async this._options = opts || {} - this._setTimeout = opts && opts.setTimeout || function (fn, delay) { return setTimeout(fn, delay) } + this._setTimeout = opts && opts.setTimeout || function (fn, delay) { + return setTimeout(fn, delay) +// if(timer1) return +// timer1 = setTimeout(function () { +// timer1 = 0 +// clearTimeout(timer2) +// timer2 = setTimeout(fn, delay) +// }, delay/2) + } } Single.prototype.write = function (value) { @@ -25,13 +34,18 @@ Single.prototype._write = function () { } Single.prototype._timeout = function (delay) { + delay = (delay == null ? Math.max( + this._options.min, + this._options.max - (Date.now() - this._ts) + ) : delay) || 10 + + if(this._next && this._next > Date.now() + delay/2) return + + this._next = Date.now() + (delay || 10) clearTimeout(this._timer) this._timer = this._setTimeout( this._write.bind(this), - delay == null ? Math.max( - this._options.min, - this._options.max - (Date.now() - this._ts) - ) : delay + delay ) } @@ -69,6 +83,3 @@ and it's a different distinction from private/public. _cb is an update. */ - - - diff --git a/test/bench.js b/test/bench.js new file mode 100644 index 0000000..4564560 --- /dev/null +++ b/test/bench.js @@ -0,0 +1,52 @@ + + +module.exports = function (name, AsyncSingle) { + var called = false + var async = AsyncSingle(function (value, cb) { + called = true + cb(null, value) + }, {min: 10, max: 20}) + + var start = Date.now() + for(var i = 0; i < 500000; i++) + async.write(i) + + console.log(name, Date.now() - start) +} + +//after a couple of runs it becomes much faster because jit has kicked in +//module.exports('closure', require('../closures')) +//module.exports('proto', require('../proto')) +//module.exports('closure', require('../closures')) +//module.exports('proto', require('../proto')) +//module.exports('proto', require('./proto')) + +function createClear() { + var timer + return { + write: function () { + clearTimeout(timer) + timer = setTimeout(function () {}, timer) + } + } +} + +function createDouble() { + var timer + return { + write: function () { + if(timer) return + clearTimeout(timer) + timer = setTimeout(function () { + timer = null + }, timer) + } + } +} + + +module.exports('closure', require('../closures')) +module.exports('proto', require('../proto')) +module.exports('clear', createClear) +module.exports('double', createDouble) +