Which is faster, For Loop or .hasOwnProperty?
for-loop, javascript, jquery, performance
Solution
If you think about it, it would make sense that the `.hasOwnProperty()` approach would be faster because it uses only 1 `for loop`.
WRONG
I was actually a little surprised. I was expecting the double loop to be slower. But I guess you can't under estimate the speed of a `for loop`.
Double Loop
While this to me would seem like the slowest, this actually ended up being the fastest benching at `7,291,083 ops/sec`
.hasOwnProperty()
I can see how this would be slower because functions are slower than statements. This benches at `1,730,588 ops/sec`
if..in
@Geuis answer included the if..in statement and thought I would test the speed of that which would seem the fastest but benching at `2,715,091 ops/sec` it still doesn't beat the for loops.
Conclusion
For loops are fast. The double loops runs more than 4 times faster than using `.hasOwnProperty()` and almost 3 times faster than using the `if..in` condition. However, the performance is not really noticeable; so is speed really that important that you have the need to complicate things. In my opinion the `if..in` method is the way to go.
Test this yourself in your browser. I was using `Google Chrome 28`.
Update
It is important to note that using an `for..in` declaration will give you the best performance.
Problem
I was working on a project where I needed to pull a list of excluded users out of a giant list of user data. It made me wonder if it is faster to use a double `for loop` with excluded id's in an `array`. Or if putting the id's in object properties and using `.hasOwnProperty()` is faster. ``` var mainList = LARGE JSON OBJECT OF DATA. var eArray = ["123456","234567","345678","456789","012345"]; var eObject = {"123456":"0","234567":"0","345678":"0","456789":"0","012345":"0"}; ``` Using the Double `For Loop` Approach: ``` for(i=0; i < mainList.length; i++){ for(j=0; j < eArray.length; j++){ if(mainList[i]['id'] === eArray[j]){ //Do Something } } } ``` Using the `.hasOwnProperty()` Approach: ``` for(i=0; i < mainList.length; i++){ if(eObject.hasOwnProperty(mainList[i]['id'])){ //Do Something } } ``` I realize there are other ways to make the loops faster, like storing lengths in variables. I've tried to simplify this. Thanks for any information.