Performance of JavaScript Instantiation Patterns

JavaScript Instantiation Patterns vary in their runtime performances. By opening up the CPU profiler in Chrome, we can easily object allocations and memory use for each pattern.

The Test

We created four different JavaScript programs that create two different data structures : Queue and Stack that have three methods to add to the stack, remove from the stack, and to get the size of the stack

Stack Class

Screen Shot 2015-07-03 at 4.30.11 PM

Queue Class

Screen Shot 2015-07-03 at 4.30.22 PM

The test makes many calls to the class and creates the object.Screen Shot 2015-07-03 at 4.29.49 PM

Functional

Most of us know functional instantiation to be the easiest pattern to follow since objects are both created and defined, along with properties and methods and return values.

Functional

Stack Calls

Time: 302.2 ms

Queue Calls

Time: 309.3 ms

In Functional instantiation, when an object is created, it also creates the methods, resulting in duplicate methods and thus, a longer time needed to run the program. In addition, when the timeline is examined more closely, we can see that .push and .size are called a whole bunch of times, adding to the total time.

Functional-Shared

Think of this one as a pattern that creates a house that stores all methods and all objects created will point to those methods

SharedFunctional

Stack Calls

Time: 304.1 ms

Queue Calls

Time: 299 ms

This pattern has a shared object that points to a method. The drop in the amount of calls to .push drops significantly because of this factor.

Prototypal

Prototypal works the same way as Functional-Shared, but the interpreter automatically generates a method declaration, therefore omitting the need for a var objMethods = {}. Through the use of a fallbacks, Prototypal ensures that if a method is called on an object, and that method does not exist, it will then check the prototype property for a fallback method.

Prototypal

Stack Test

Time: 299 ms

Queue Test

Time: 292.3 ms

Pseudoclassical

This style wraps all the wonderful functionality of prototypal and functional shared by allowing the interpreter to automatically assign the “this” to newly created objects, therefore omitting the need for the use of Object.Create().Screen Shot 2015-07-03 at 4.16.09 PM

Stack Test

Time: 296.6 ms

Queue Test:

Time: 304.6 ms

Pseudoclassical, with its neat interpreter magic runs the fastest because the interpreter automatically declares methods once.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s