为什么大多数 JavaScript 原生函数都比它们的原始实现慢? [英] Why most JavaScript native functions are slower than their naive implementations?

查看:19
本文介绍了为什么大多数 JavaScript 原生函数都比它们的原始实现慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到一些 测试 原生 JavaScript 函数通常比简单实现慢得多.这背后的原因是什么?

I've noticed though some tests that native JavaScript functions are often much slower than a simple implementation. What is the reason behind that?

推荐答案

看了ECMA-262.与简单的自我实现相比,本地实现似乎在错误处理和功能方面做得更多.

After looking at ECMA-262. It seems that the native implementations just do more in terms of error handling and features than the simple self-implementations.

例如,查看 MDN 上 map 的 polyfill 实现:Array.prototype.map().它基于 ECMA-262 中指定的相同算法.更新您的示例以使用此算法现在可以使本机实现更快——尽管只是略微:map-native-vs-implemented.

For instance, check out the polyfill implementation of map on MDN: Array.prototype.map(). It's based off the same algorithm specified in ECMA-262. Updating your example to use this algorithm now makes the native implementation faster—although just slightly: map-native-vs-implemented.

此外,map 可能不是最好的测试示例,因为它在本机代码和提供的 lambda 函数之间来回跳动.

Also, map might not be the best example to test since it's bouncing back and forth between native code and the provided lambda function.

我本来期望原生 concat 函数有更好的性能.尽管如此,查看 ECMA-262 我们可以看到它也只是做得更多.查看 15.4.4.4 节中的算法,我们可以看到它处理了一些额外的情况.例如组合多个参数——一些是数组,一些是其他类型:

I would have expected better performance for the native concat function. Nevertheless, looking at ECMA-262 we can see it also just does more. Looking at the algorithm in section 15.4.4.4, we can see that it handles some extra cases. For instance combining multiple arguments—some being arrays and some being other types:

[1, 2, 3].concat([4, 5, 6], "seven", 8, [9, 10]);

返回

[1, 2, 3, 4, 5, 6, "seven", 8, 9, 10]

最后需要注意的是,这些都是非常基本的算法.当在庞大的数据集上或连续数千次运行此类算法时,似乎一个明显比另一个快.然而,即使在数千次迭代中执行一些额外的安全检查,也会使一种算法比不进行这些检查的算法慢得多.计算计算操作——如果您额外的错误处理和功能使循环中的代码行数增加了一倍,那么它会变慢是很自然的.

Finally it's important to note that these are pretty basic algorithms. When running such algorithms on huge data sets, or thousands of times consecutively, it may seem that one is significantly faster than the other. However, performing even a couple of extra safety checks over thousands of iterations can render one algorithm significantly slower than one that does not do those checks. Count the computational operations—if your extra error handling and features doubles the lines of code in the loop, it's only natural that it would be slower.

这篇关于为什么大多数 JavaScript 原生函数都比它们的原始实现慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆