Property Is Faster Than Method? Need Reason For It
Solution 1:
size
internally calls the length
//http://code.jquery.com/jquery-latest.js// The number of elements contained in the matched element setsize: function() {
returnthis.length;
},
So if you are using length then you are avoiding one extra method call. The Jquery docs says:
The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.
Solution 2:
I am assuming that you want to get the length of a String or the number of elements in an Array.
size()
is not a method of the Array or String objects. Thus if it exists some library or you yourself have added this method to the respective prototypes. length
on the other hand is a default property and (should) exist in any JS runtime.
Unless you cannot use length, the size function will just add unneeded overhead and I would go for the property.
Check the following to links: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/prototypehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype
Solution 3:
If you will read length
property then only time required to access an object property will be needed.
However if you will call size()
then first of all a function will be called, this function will read length
property internally and then return that value to the caller.
You can clearly see that you are doing the same thing in both cases. But if you call the function then it will include time for calling a function + returning that value too..
Solution 4:
Length returns the same thing and is slightly faster according to the jQuery documentation.
Source: http://api.jquery.com/size/
Post a Comment for "Property Is Faster Than Method? Need Reason For It"