gpt4 book ai didi

javascript - 为什么原型(prototype)函数比默认声明的函数慢 40 倍?

转载 作者:行者123 更新时间:2023-12-04 02:28:32 24 4
gpt4 key购买 nike

我玩过 jsperf.com,发现原型(prototype)函数比“默认”声明的函数慢 40 倍

String.prototype.contains = function(s){ return !!~this.indexOf(s) } = 220K ops/s

对比

function isContains(str, s) { return !!~str.indexOf(s) } = 8.5KK 操作/秒

Here's a jsperf test case

附言我知道原型(prototype)修改不是最好的情况,可以命名为“猴子修补”:)

最佳答案

我认为它很慢,因为字符串基元每次调用一个方法时都会自动用一个临时对象包装。

这也解释了 new Object("hi").foo() 相对于 "hi".foo() 的性能提升。

来自MDN docs :

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives and String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

附近:

Why can't I add properties to a string object in javascript?

String object versus literal - modifying the prototype?

关于javascript - 为什么原型(prototype)函数比默认声明的函数慢 40 倍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29495201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com