将方法添加到本机JavaScript对象的性能影响是什么?(What is the performance impact of adding methods to native JavaScript

编程入门 行业动态 更新时间:2024-10-27 16:25:33
将方法添加到本机JavaScript对象的性能影响是什么?(What is the performance impact of adding methods to native JavaScript objects?)

我意识到向本地JavaScript对象(对象,函数,数组,字符串等)添加方法被某些人认为是不好的做法,但是是否也有与此相关的性能问题?

本地对象的实例是否需要更长的时间来创建和/或使用更多的内存,如果它们的原型已经使用其他方法进行了扩展?

I realize that adding methods to native JavaScript objects (Object, Function, Array, String, etc) is considered bad practice by some, but is there also a performance hit associated with this?

Would instances of native objects take longer to create and/or use up more memory if their prototype has been extended with additional methods?

最满意答案

本地对象的实例是否需要更长的时间来创建和/或使用更多的内存,如果它们的原型已经使用其他方法进行了扩展?

不。这些事情都不应该发生:每个对象都必须保持对其原型的引用,但如果将更多属性添加到其引用的对象中,则该引用不会变得更大或者不再需要检索。

现在,如果要向prototype添加足够的其他方法,它可能会开始影响在该类型的对象上查找方法所需的时间。 这会因实现而有所不同,但如果您发现有差异,我会感到震惊(我怀疑您会在它对运行时速度有显着影响之前很久才试图记住所有这些附加方法的名称)。


编辑: 这是一个快速和丑陋的测试 - 在Array.prototype对象中添加500K自定义方法之前和之后,它会创建500K个数组实例。 没有可观的区别; 别担心...

Would instances of native objects take longer to create and/or use up more memory if their prototype has been extended with additional methods?

No. Neither of those things should happen: each object must maintain a reference to its prototype, but that reference won't get any larger or take any longer to retrieve if more properties are added to the object it references.

Now, if you were to add enough additional methods to the prototype, it might start to impact the time needed to look up methods on the objects of that type. This will vary by implementation, but i would be shocked if you ever noticed a difference (i suspect you'd drive yourself mad trying to remember the names of all those additional methods long before it had a noticeable impact on runtime speed).


Edit: here's a quick & ugly test - it creates 500K instances of Array before and after adding 500K custom methods to the Array.prototype object. No appreciable difference; no worries...

更多推荐

本文发布于:2023-07-15 15:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1115288.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:本机   对象   性能   方法   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!