Memoize method bind

JavaScript performance comparison

Test case created by D[oa]vid Weisz

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  "use strict";
  
  const _caches = new WeakMap();
  
  const JOINWITH = "-_-";
  
  function _getCache(context) {
  	if (!_caches.has(context)) {
  		_caches.set(context, new Map());
  	}
  	return _caches.get(context);
  }
  
  function memoBind(context, methodName, ...args) {
  	const cache = _getCache(context);
  	const cacheKey = `${methodName}-${args.join(JOINWITH)}`;
  
  	if (cache.has(cacheKey)) {
  		return cache.get(cacheKey);
  	}
  
  	const func = context[methodName].bind(context, ...args);
  	cache.set(cacheKey, func);
  	return func;
  }
  const myObject = {
      myMethod: function(a,b){console.log(`${a}-${b}`)}
  }
  const myObject2 = {
      myMethod: function(a,b){console.log(`${a}-${b}`)}
  }
  const myObject3 = {
      myMethod: function(a,b){console.log(`${a}-${b}`)}
  }
  const myObject4 = {
      myMethod: function(a,b){console.log(`${a}-${b}`)}
  }
  
  
  const arg1 = 'one';
  const arg2 = 2;

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
memoBind
const comp ={
a: memoBind(myObject,'myMethod', arg1, arg2),
b: memoBind(myObject2,'myMethod', arg1, arg2),
c: memoBind(myObject3,'myMethod', arg1, arg2),
d: memoBind(myObject4,'myMethod', arg1, arg2)
}
pending…
function.bind
const comp =
{
a: myObject.myMethod.bind(myObject, arg1, arg2),
b: myObject2.myMethod.bind(myObject2, arg1, arg2),
c: myObject3.myMethod.bind(myObject3, arg1, arg2),
d: myObject4.myMethod.bind(myObject4, arg1, arg2)
}
pending…
Arrow function
const comp ={
a: () => myObject.myMethod(arg1, arg2),
b: () => myObject2.myMethod(arg1, arg2),
c: () => myObject3.myMethod(arg1, arg2),
d: () => myObject4.myMethod(arg1, arg2)
}
pending…

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

Compare results of other browsers

0 Comments