Is it good to use _.findWhere always?
Deepika Banoth
Posted on November 19, 2019
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 🙂
Posted on November 19, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.