简体   繁体   English

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

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

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() ? 在这种情况下,使用lodash _.size()有什么好处? Does it perform any differently than the (native...?) length property? 它与(native ...?)长度属性的执行方式有何不同?

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大小而不是length属性有什么好处吗?

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.length so 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 length is being used when a number on the stack could have been used to achieve the same goal. 在性能文章中,性能问题是当堆栈上的数字可用于实现相同的目标时,正在使用length的属性查找。 In other words, the solution was not to look for a faster property, but to avoid the property altogether when it could be done. 换句话说,解决方案不是寻找更快的属性,而是在可以完成时完全避免属性。

The size() function is most useful in chains, when you need the size of the result. 当您需要结果的大小时, size()函数在链中最有用。 There's no point in unpacking everything using value() just to get the size. 使用value()解压缩所有内容只是为了获得大小。 For example: 例如:

_(_.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()是关于代码简洁,而不是性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM