为什么大多数JavaScript本地函数比其朴素的实现慢? [英] Why most JavaScript native functions are slower than their naive implementations?

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

问题描述

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

组织/出版物/标准/ ECMA-262.htm> ECMA-262 。看起来,本地实现只是在错误处理和功能方面比简单的自我实现更多

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


另外, map 可能不是测试的最佳示例,因为它在两者之间来回跳动本地代码和提供的lambda函数。



我希望本地的 concat 函数具有更好的性能。不过,看着ECMA-262,我们可以看到它也只是更多。看第15.4.4.4节中的算法,我们可以看到它处理了一些额外的情况。例如,结合多个参数 - 一些是数组,另一些是其他类型:

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



返回

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



最后需要注意的是这些都是非常基本的算法。当在巨大的数据集上运行这样的算法,或者连续数千次运行这样的算法时,似乎一个比另一个快得多。但是,在数千次迭代中执行几次额外的安全检查可以使一种算法比不执行这些检查的算法慢得多。对计算操作进行计数 - 如果额外的错误处理和特性使循环中的代码行数加倍,那么它很自然会变慢。


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

解决方案

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.

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.

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.

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]);

returns

[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天全站免登陆