DEV Community

Cover image for Is it good to use _.findWhere always?
Deepika Banoth
Deepika Banoth

Posted on

Is it good to use _.findWhere always?

We spent a lot of time optimizing our code to increase performance of UX of our app. But still, we thought it was not up to the mark as it was taking little more time to load UI whereas getting the response from API was in less than a second. We felt something was wrong.

We decided to check on a particular page what part of code is taking a lot of time using performance panel from chrome dev tool.

We were all astonished after looking at the result. It was _.findWhere which was taking a lot of time. We use underscore.js (a javascript library which provides helper functions) throughout our app. We used _.findWhere in some places where there is a better alternative which executes fast.

So is it bad to use _.findWhere?

The answer is NO.
There is nothing wrong in using _.findWhere, but you also need to know when to not use it.

Suppose you have an array of objects, let's say example_array, you want to find a particular object in that array only once. Then using _.findWhere is good.

But you have a scenario where you want to find different objects from example_array in different places of your controller, then using _.findWhere would be a bad idea. Why do you want to parse the same array by looping it again and again?

Instead, index the array and get the object immediately. You will get your required result in no time.

When we executed this change by replacing _.findWhere with indexed objects. Performance of our page was improved. The page was loading noticeably faster than before 🙂

So be sure when to use _.findWhere and when not to use.

I hope this post helps 🙂

Top comments (2)

Collapse
 
chiangs profile image
Stephen Chiang • Edited

If you're only looking for the first instance of the object in the array, you can just use the native method array.find if you want all the instances of that object from the array you can use array.filter ... I don't think you don't need lodash for that operation.

Collapse
 
riturajcse profile image
Rituraj

Informative post indeed, but just a thought with ES 7 in hand now most of the things that we do using libraries like underscore or lodash can be done using new features of ES 7 in one way or another and in most cases these native JS functions will be faster. Yes but obviously as your post states this all varies scenario to scenario and hence we should keep our eyes open :) .