Javascript 对象与基元
我目前正在 OOP Javascript 方面进行大量开发。 特别是,我经常处理坐标和尺寸,并且定义了许多变量作为对象,如下所示:
coords = {
x:10,
y:15
};
dimensions = {
width:500,
height:250
}
但我想知道将值指定为单独的原始变量是否会更快/更有效:
coordX = 10;
coordY = 15;
dimWidth = 500;
dimHeight = 240;
有人可以简要解释一下每种变量字符串方法的优点/缺点吗? 在可用性方面,我发现对象更容易,因为您可以将相关值分组在一起;尽管我认为它速度较慢。 但它比定义更多变量更慢,或者占用更多内存吗?
干杯。
编辑: 哇!我没想到会有这么多回复,尤其是这么快!谢谢大家的回复。
似乎任何性能差异都是可以忽略的,但这可能只适用于简单的脚本。 我拥有的是一个恒定循环,它需要以尽可能高的 FPS 运行。每个循环使用许多对象变量来存储数据,如上所示。那么在这些情况下是否存在潜在的性能问题呢?
I'm currently doing a lot of development in OOP Javascript.
In particular, I'm dealing with coordinates and dimensions a lot and I have many variables defined, as objects, like so:
coords = {
x:10,
y:15
};
dimensions = {
width:500,
height:250
}
But I'm wondering if it would be quicker/more efficient to specify the values as separate, primitive, variables:
coordX = 10;
coordY = 15;
dimWidth = 500;
dimHeight = 240;
Could someone please briefly explain the advantage/disadvantage of each method of string the variables?
Usability-wise, I find objects easier, as you can group related values together; although I gather that it is slower.
But is it slower, or take up more memory, than defining more variables?
Cheers.
EDIT:
Wow! I never expected this many responses, especially so quickly! Thank you all for your responses.
It seems like any performance differences are negatable, but this may only apply to simple scripts.
What I have is a constant loop, which needs to run at the highest FPS possible. Each loop uses many object variables for storing data, like above. So is there the potential for performance issues in these circumstances?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用最适合当前问题的任何方法。
如果在您的代码中使用对象有意义,请使用一个对象。如果变量更有意义,请使用它们。
You use whatever is most appropriate for the problem at hand.
If it makes sense in your code to use an object, use one. If variables make more sense, use them.
性能不应该是一个问题——属性是在对象上声明的,不需要原型链来访问它们(JavaScript 引擎在这个领域也变得越来越高效)。
在这种情况下,我个人更喜欢使用面向对象方法,因为它允许对值进行逻辑分组,这对于查看您的代码的任何其他开发人员来说会更清晰(并且,如果您像我一样,可能您在几个月的时间!)。
Performance should not be an issue - the properties are declared on the object and no prototype chain is necessary to access them (also javascript engines are becoming more and more performant in this area).
I'd personally prefer to use the OO approach in this situation, since it allows a logical grouping of values, which will be clearer to any other developers who look at your code (and, if you're anything like me, possibly you in a couple of months time!).