The article (link below) suggests that using the length property on a string creates an object reference which unnecessarily slows the function down.
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?
If you're counting an array or keys in an object, is there any benefit to using lodash size instead of the length property?
The Lodash size is about 72.5 KB.
Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. You can create composite functions, manipulate objects and arrays. To try it out, you can npm/yarn/bower install it for the backend and you can use the CDN in the frontend.
Lodash is extremely well-optimized as far as modern JS goes, but, as you may know, nothing can be faster than native implementation. Even if Lodash uses the same API under-the-hood, function call overhead is still present. Some might say that these are just some micro-optimizations.
Length is a property of objects that are an instance of type Array. And objects have properties and this property keeps track of the length (automatically for the most part). So length is like an object key as in when you call it, it will return its value.
From the lodash sources, _.size()
is implemented as:
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.
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. 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. There's no point in unpacking everything using value() just to get the size. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With