Thunks

Benchmark created by sorella on


Setup

function delay(t) {
      return [false, t]
    }
    function force(t) {
      if (t[0]) return t[1]
      else      { t[0] = true
                  t[1] = t[1]()
                  return t[1]
                }
    }
    
    function Thunk(t) {
      this.forced = false
      this.value  = t
    }
    Thunk.prototype.force = function() {
      if (this.forced) return this.value
      else             { this.forced = true
                         this.value  = this.value()
                         return this.value
                       }
    }
    
    
    function cons(a, b) {
      return [a, b]
    }
    
    function iterate(f, a) {
      return cons(a, delay(function(){ return iterate(f, f(a)) }))
    }
    function take(n, xs) {
      var result = []
      while (n-- > 0) {
        result.push(xs[0])
        xs = force(xs[1])
      }
      return result
    }
    
    function iterate2(f, a) {
      return cons(a, new Thunk(function(){ return iterate2(f, f(a)) }))
    }
    function take2(n, xs) {
      var result = []
      while (n-- > 0) {
        result.push(xs[0])
        xs = xs[1].force()
      }
      return result
    }
    
    var numbers, xs
    var numbers1 = iterate(function(a){ return a + 1 }, 0)
    var numbers2 = iterate2(function(a){ return a + 1 }, 0)

Test runner

Ready to run.

Testing in
TestOps/sec
Arrays as promises
xs = take(1000, numbers1)
ready
Objects as promises
xs = take2(1000, numbers2)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by sorella on