为什么本机数组函数比循环慢得多 [英] Why are native array functions are so much slower then loop

查看:112
本文介绍了为什么本机数组函数比循环慢得多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在于标题,但这里有一个更长的解释。

The question is in the title, but here is a longer explanation.

很久以前我学到了一些不错的javascript函数,如reduce,filter,map 等等。我真的很喜欢它们并开始经常使用它们(它们看起来很时尚,我认为因为它们是原生功能,它们应该比旧的for循环更快)。

Long time ago I learned some nice javascript functions like reduce, filter, map and so on. I really liked them and started to use them frequently (they look stylish and I thought that because they are native functions they should be faster than my old for loops).

最近我需要执行一些重js计算,所以我决定检查它们的速度有多快,令我惊讶的是它们没有更快,它们慢得多(慢3到25倍)

Recently I needed to perform some heavy js computations, so I decided to check how faster are they and to my surprise they are not faster, they are much much slower (from 3 to 25 times slower)

此外,我还没有检查过每个函数是我的jsperf测试:

Also I have not checked for every function by here are my jsperf tests for:

  • filter (25 times slower)
  • reduce (3 times slower)
  • map (3 times slower)

那么为什么原生函数比旧循环慢得多如果他们没有做任何更好的事情,那就创造它们。

So why are native functions are so much slower then old loops and what was the point of creating them if they are not doing anything better.

我认为速度损失是由于邀请它们内部功能的阳离子,但它仍然不能证明这种损失。此外,我不明白为什么用这些函数编写的代码更具可读性,更不用说每个浏览器都不支持它们。

I assume that the speed loss is due to the invocation of the function inside of them, but still it does not justify such loss. Also I can not see why the code written with these functions is more readable, not to mention, that they are not supported in every browser.

推荐答案

我认为在某些时候,它归结为这些本机函数比它们的优化更多的糖。

I think at some point it comes down to the fact that these native functions are more sugar than they are optimizations.

这与使用 Array.prototype.splice 的说法不同,而不是循环并自行完成实现显然将能够在你自己的能力范围内做更多的事情(在内存中)。

It's not the same as say using Array.prototype.splice rather than looping over and doing it yourself where the implementation is obviously going to be able to do far more under the hood (in memory) than you yourself would be able to.

在某些时候使用filter,reduce和map,浏览器必须遍历你的数组并对其中包含的值执行一些操作(就像你做一个循环)。它不能减少实现相同目的所需的数量(它仍然循环并执行操作),但它可以为您提供更令人满意的API并提供错误检查等,这将增加时间。

At some point in time with filter, reduce and map the browser is going to have to loop over your array and perform some operation on the value contained within it (just as you do with a loop). It can't reduce the amount it has to do to achieve the same ends (it's still looping and performing an operation) but it can give you a more pleasing API and provide error checking etc that will increase the time.

这篇关于为什么本机数组函数比循环慢得多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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