dimanche 16 septembre 2018

Performance optimization in "Factory Design Pattern" in JavasScript

I want to use factory design pattern in my application and use of some of its benefit such as readability, flexibility, scalability and correct binding of "this" operator" during development. As my application generates html code in loading of my webpage, the performance and memory usage of creating objects is important in my case. please take a look at the following example;

// Factory Design with Delegation
const car = function( color ) 
{
        const CarPrototype = function( color )
        {
                const carPrototype = {};
                
                carPrototype.color = color;
                // Private function
                function internal()
                {
                        console.log( "internal" );
                        // ...
                }
                
                // Public function
                carPrototype.gas = function()
                {
                        internal();
                        // ...
                }
                
                carPrototype.break = function()
                {
                        // ...
                }
                
                return carPrototype;
        }
        return Object.create( CarPrototype( color ) );
}

// Traditional constructor function
const Car = function( color )
{
        this.color = color;
        // ...
}

Car.prototype.internal = function()
{
        console.log( "internal" );
        // ...
}

Car.prototype.gas = function()
{
        this.internal();
        // ...
}

Car.prototype.break = function()
{
        // ...
}


function myFunction()
{

const mazdaF = car( "red" );

const mazdaT = new Car( "red" );
 
console.log( mazdaF, mazdaT );

}
<html>
  <head></head>
  <body onload="myFunction()">
  </body>
</html>

The result of running the above code is shown below.

enter image description here

In addition, performance test result is shown here Performance result.

I want to know whether I am using a correct pattern for my case or not. In case, what should I do to improve performance?

Aucun commentaire:

Enregistrer un commentaire