Javascript lodash _.size() 比 JS 长度属性快吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31014793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:05:05  来源:igfitidea点击:

Is lodash _.size() faster than JS length property?

javascriptsizelodash

提问by claireablani

The article (link below) suggests that using the length property on a string creates an object reference which unnecessarily slows the function down.

这篇文章(下面的链接)建议在字符串上使用 length 属性会创建一个对象引用,这会不必要地减慢函数的速度。

http://www.webreference.com/programming/javascript/jkm3/2.html

http://www.webreference.com/programming/javascript/jkm3/2.html

In this context, what is the advantage of using lodash _.size() ? Does it perform any differently than the (native...?) length property?

在这种情况下,使用 lodash _.size() 有什么好处?它的表现与(本机...?)长度属性有什么不同吗?

If you're counting an array or keys in an object, is there any benefit to using lodash size instead of the length property?

如果您正在计算对象中的数组或键,使用 lodash size 而不是 length 属性有什么好处?

回答by DocMax

From the lodash sources, _.size()is implemented as:

从 lodash 来源,_.size()实现为:

function size(collection) {
  var length = collection ? getLength(collection) : 0;
  return isLength(length) ? length : keys(collection).length;
}

For an array, the first line is indirectly doing collection.lengthso that _.size()is, if anything, a little (tiny) bit slower.

用于阵列,第一行被间接地这样做collection.length使得_.size(),如果有的话,一点(微小的)位慢。

In the performance article, the performance problem is that the property lookup of lengthis being used when a number on the stack could have been used to achieve the same goal. In other words, the solution was not to look for a faster property, but to avoid the property altogether when it could be done.

在性能文章中,性能问题是length当堆栈上的一个数字可以用来实现相同的目标时,正在使用的属性查找。换句话说,解决方案不是寻找更快的属性,而是在可以完成时完全避免该属性。

回答by Adam Boduch

The size()function is most useful in chains, when you need the size of the result. There's no point in unpacking everything using value()just to get the size. For example:

尺寸()函数是在链最有用的,当你需要的结果的大小。使用value()解包所有内容只是为了获取大小是没有意义的。例如:

_(_.range(10))
    .filter(function(item) { return item % 2; })
    .size();

As opposed to the longer form:

与较长的形式相反:

_(_.range(10))
    .filter(function(item) { return item % 2; })
    .value()
    .length;

This function also makes it easier to find the size of an object:

此函数还可以更轻松地找到对象的大小:

_.size({ a: 1, b: 2 });

As opposed to:

与之相反:

Object.keys({ a: 1, b: 2 }).length;

size()is about code brevity, not performance.

size()是关于代码简洁,而不是性能。