What is the difference between the two?
So I know that array.size()
is a function while array.length
is a property. Is there a usecase for using one over the other? Is one more efficient? (I would imagine .length
to be significantly faster as it is a property rather then a method call?) Why would one ever use the slower option? Are there some browsers that are incompatible with one or the other?
var x = []; console.log(x.size()); console.log(x.length); console.log(x.size()==x.length); x =[1,2,3]; console.log(x.size()); console.log(x.length); console.log(x.size()==x.length);
Will print:
0, 0, true 3, 3, true
length() is a method used by Strings (amongst others), it returns the number of chars in the String; with Strings, capacity and number of containing elements (chars) have the same value. size() is a method implemented by all members of Collection (lists, sets, stacks,...).
Size and length both returns the number of element in an object. But length is faster than the size because length is a property and size is a method.
The size of an array object is always equal to the second template parameter used to instantiate the array template class (N). Unlike the language operator sizeof, which returns the size in bytes, this member function returns the size of the array in terms of number of elements.
One is length that is used with Arrays, other is the length () that is used with Strings and one more is the size () that is used with ArrayList: In Java, Arrays do not use methods and are one of the earliest primitive used to know the length of Array variables.
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size
method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).
.size()
is not a native JS function of Array
(at least not in any browser that I know of).
.length
should be used.
.size()
does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array
prototype.
There might be some plugin on your browser that is mucking with the Array
prototype.
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