methodvsclosure

Benchmark created by bonafidebob on


Description

2D vector class as closures vs traditional constructors

Setup

// closure class
    function createVector(x, y) {
      var coords = Object.seal({ x: x, y: y });
    
      function scale(factor) {
        coords.x *= factor;
        coords.y *= factor;
      }
    
      function addVector(anotherVector) {
        coords.x += anotherVector.getX();
        coords.y += anotherVector.getY();
      }
    
      function getX() { return coords.x }
      function getY() { return coords.y }
    
      return Object.freeze({
        getX: getX,
        getY: getY,
        scale: scale,
        addVector: addVector
      });
    };
    
    // traditional constructor and prototype
    function Vector(x, y) {
        this.x = x;
        this.y = y;
        Object.seal(this);
    };
    
    Vector.prototype.scale = function(factor) {
        this.x *= factor;
        this.y *= factor;
    };
    
    Vector.prototype.addVector = function(anotherVector) {
        this.x += anotherVector.getX();
        this.y += anotherVector.getY();
    };
    
    Vector.prototype.getX = function() { return this.x; };
    Vector.prototype.getY = function() { return this.y; };
    
    Object.freeze(Vector.prototype);
    Object.freeze(Vector);

Test runner

Ready to run.

Testing in
TestOps/sec
Create closure
createVector(1,2);
ready
Create instance
new Vector(1,2);
ready
Use closure
v1 = createVector(1,2);
v2 = createVector(3,4);
v1.scale(2);
v2.scale(0.5);
v1.addVector(v2);
v2.addVector(v1);
v1.getX();
v1.getY();
v2.getX();
v2.getY();
ready
Use instance
v1 = new Vector(1,2);
v2 = new Vector(3,4);
v1.scale(2);
v2.scale(0.5);
v1.addVector(v2);
v2.addVector(v1);
v1.getX();
v1.getY();
v2.getX();
v2.getY();
ready

Revisions

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

  • Revision 1: published by bonafidebob on