If I’m looping and referencing a variable that’s kept in localStorage, should I create a locally scoped variable (outside the loop) and set it equal to the localStorage variable for performance reasons?
If I’m looping and referencing a variable that’s kept in localStorage, should I create
Share
If you are referencing the same local storage value multiple times within a function, then assign it to a local variable for the duration of that function. This is no different than any other value that takes some work to retrieve (like the value of an input field in the DOM). If you need the value multiple times within the same function, then put it’s value in a local variable and use it from there. Your code will probably be more compact and execute faster too.
There should be no reason to cache it globally in a persistent global variable as it’s already globally accessible from local storage so there’s really no reason to add a new global for it. Just retrieve the value in each function that you need it in. The only exception I could imagine to this would be a micro-performance-optimization in a rare circumstance. Generally, it’s better not to make your own global copy of things that are already globally available.