JavaScript 类内存使用情况
所以我一直在做一些类似 JavaScript 类的东西,例如
MyClass = function()
{
var x;
this.sayX = function()
{
alert(x);
}
}
但我也看到了
MyClass = function()
{
this.x = 0;
}
MyClass.prototype.sayX = function()
{
alert(this.x);
}
最大的问题是,我是否仍在浪费当今 JavaScript 引擎中的内存空间,或者它们是否能够看到我的方法中的重复并优化它们出去?我问的原因是因为我宁愿进行适当的数据隐藏,而不必在所有内容前面加上“this”前缀。
So I've been doing some JavaScript class-like stuff such as
MyClass = function()
{
var x;
this.sayX = function()
{
alert(x);
}
}
but I've also seen
MyClass = function()
{
this.x = 0;
}
MyClass.prototype.sayX = function()
{
alert(this.x);
}
The big question is, am I still wasting memory space in today's JavaScript engines, or are they capable of seeing the duplication in my method and optimizing them out? The reason I ask is because I'd rather do proper data hiding and not have to prefix absolutely everything with 'this'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个的内存占用总是更大。将原型视为所有实例都可以使用的共享方法包。它很有效,因为您不必为每个实例创建一个新函数,而是重用内存中已有的方法。
好消息是您展示的两种方法可以结合起来。
但就您处理小型代码库而言,您不应该担心内存使用情况。您甚至可以使用类似的模式
注意,我故意将 myClass 更改为小写,因为它不再是构造函数,并且调用时无需使用
new
!UPDATE - 第三种模式非常适合您的需求:
The memory footprint of the first one will always be larger. Consider
prototype
as a shared package of methods that all instances can use. It is effective because you don't create a new function for every instance, but you're reusing the existing method already in memory.The good news is that the two ways you showed can be combined.
But as far as you're dealing with small codebase, you shouldn't worry about memory usage. You can even use patterns like
Note, I intentionally changed myClass to lowercase, because it's no longer a constructor function and there's no need to use
new
when invoking!UPDATE - there's a third pattern which well suits your needs:
稍后重新审视这一点,但事实证明 V8 足够聪明,它不会在第一种方法中创建该函数的多个实例。转到隐藏课程 :D
http://www.youtube.com/watch?v=hWhMKalEicY
Revisiting this a huge amount later, but it turns out V8 is smart enough that it doesn't create multiple instanced of that function in the first method. Go hidden classes :D
http://www.youtube.com/watch?v=hWhMKalEicY