DEV Community

Cover image for Class vs Function Objects- Memory comparison (Part 2)
Manoj
Manoj

Posted on • Updated on

Class vs Function Objects- Memory comparison (Part 2)

Introduction

It is a common practise for JavaScript developers to use function definition to create Objects rather than class definition.

Note
Here we are going to compare the memory size of objects created using a single definition type (i.e either class definition or function definition).

Expectation

And it may seem that the objects created through both the ways should be similar in size, but are they really similar or one way is more memory efficient than the other?
Lets find out.

Steps

To start with, we created 1 million JavaScript Objects using class definition and 1 million JavaScript Objects using function definition.

We compared both and the result is surprising.

Objects created with class

Memory snapshot (using chrome dev tools) - 1 million objects

Image description

// Create a basic class with name MyClass
class MyClass {
    constructor(arg) {
        this.value = arg;
    }
    method1() {
        console.log("lorem ipsum demo1");
    }
    method2() {
        console.log("very different lorem");
    }
}
Enter fullscreen mode Exit fullscreen mode

Objects created with function

Memory snapshot (using chrome dev tools) - 1 million objects

Image description

// Create a basic function with name MyFunction
function MyFunction(arg) {
    this.value = arg;

    this.method1 = function() {
        console.log("lorem ipsum demo1");
    }

    this.method2 = function() {
         console.log("very verdifferent lorem");
    }
}
Enter fullscreen mode Exit fullscreen mode

Results

Name Detail
Objects created with class 16 * 10^6 Bytes
Objects created with function 24 * 10^6 Bytes

Objects created with function have a far greater size.

Now, lets see what if we create objects with nested function structure

Objects with nested functions

Memory snapshot - 1 million object instances

Image description

// Create a basic function with name MyFunction
function MyFunction_withInnerFunction(arg) {
    this.value = arg;
    function method1() {
        console.log("lorem ipsum demo1");
    }
    function method2() {
         console.log("very verdifferent lorem");
    }
}
Enter fullscreen mode Exit fullscreen mode

Overall results

  • The shallow size** of objects created with function is high.
  • The retained size** of objects created with function is very high.
Name Detail
Objects created with class 16 * 10^6 Bytes
Objects created with function 24 * 10^6 Bytes
Objects created with nested function 16 * 10^6 Bytes

**Terminology

  • Shallow size - size of memory held by object itself
  • Retained size - size of memory held by object and memory of its references (not memory held by referenced objects but the references itself).

Reference:

Top comments (0)