Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript prototype usage performance [duplicate]

I want to learn the advantages of using JavaScript prototype. Object prototype usage is increasing performance. I want to see this by usage of memory.

Case-1

    var Foo1 = function (name) {
        this.name = name;
        getFirstName = function() { return "name1"; };
        getLastName = function() { return "name2"; };
    };
    for (var i = 0; i < 1000; i++) {
        var foo1 = new Foo1();
    }

Case-2

    var Foo2 = function (name) {
        this.name = name;
    };

    Foo2.prototype = {
        getFirstName: function () { return "name1"; },
        getLastName: function () { return "name2"; },
    };

    for (var i = 0; i < 1000; i++) {
        var foo2 = new Foo2();
    }
  1. which case is using memory more than another?

  2. Can I learn memory usage of cases?

  3. What is the difference about memory usage of cases?

like image 827
bayramucuncu Avatar asked Jan 30 '26 05:01

bayramucuncu


1 Answers

If you define a function or an object to belong to the prototype then it's shared by all instances and creating an object with new does not create it's own instance of the function/object. In this sense defining something to belong to the prototype uses less memory. The precise difference would be that case 1 (look at comments below because your definition is not proper) would create 1000 instances of each function. Case 2 (again look at the comments below) would create only 1 instance of each function.

However case 2 is not defining in the prototype. You're essentially redefining the prototype there. The correct usage would be:

function Foo2 (name) {
    this.name = name;
};

Foo2.prototype.getFirstName = function () { return "name1"; };
Foo2.prototype.getLastName = function () { return "name2"; };

Your case 1 is also not correctly defined in terms of what you're trying to achieve because getFirstName and getLastName are not defined through this (the instance).

like image 90
Konstantin Dinev Avatar answered Jan 31 '26 19:01

Konstantin Dinev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!