The cost of private members via closures in JavaScript
Comments
JavaScript supports private member variables through closures but you should think it over before you use them.
Unfortunately this approuch is significantly slower and consumes more memory too.
If you are going to create many instances of a function constructor, you’d better not use private members due to performance
loss and higher memory consumption. I made this test to demonstrate you the performance differences.
There are four function constructors written in different ways. The first one is the simplest with two public member variables.
As we know, in OOP we should not expose member variables to the outer world. They should be private variables and getter/setter methods
should be written to them. Although this can be achieved easily in other OOP languages such as Java or C#, this approuch in JavaScript
has a significant performance drawback.
We test how much time does it take to the browser to create 1000 instances from the function constructors.
The time is measured and displayed at the bottom of the function constructors.
It is interesting to test this page in other browsers to compare how much faster or slower the code is executed in them.
There are four function constructors written in different ways. The first one is the simplest with two public member variables. As we know, in OOP we should not expose member variables to the outer world. They should be private variables and getter/setter methods should be written to them. Although this can be achieved easily in other OOP languages such as Java or C#, this approuch in JavaScript has a significant performance drawback.
We test how much time does it take to the browser to create 1000 instances from the function constructors. The time is measured and displayed at the bottom of the function constructors.
It is interesting to test this page in other browsers to compare how much faster or slower the code is executed in them.