Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables VS localStorage in web app and memory issues

I'm wondering which would be better practice. Polluting the global namespace with global variables for intra-session persistence or using localStorage instead?

So in other words set a global variable on launch, change its value in a function when required and reference it in a third function, or use localStorage.setItem then localStorage.removeItem when the value is no longer needed?

Will doing either one increase memory efficiency?

like image 259
OliverJ90 Avatar asked Dec 04 '14 19:12

OliverJ90


1 Answers

LocalStorage is primarily for persistent data across sessions. In your case, as your looking for an intra-session persistence, global variables have clear advantages.

I will start with cons of global variables first.

  • It uses the global namespace, any third party js code can manipulate it
  • A page refresh can wipe off your data

Well, that's it. If we consider the cons of LocalStorage, the list will raise your eyebrows.

  • set and get are slow and can be a performance bottleneck for large datasets
  • only strings are allowed; you may have to serialize your data before setting

I would surely vote up for LocalStorage if your use case involved inter-session storage. However, in your scenario, the only benefit you see is the removeItem function for which you have the delete counterpart for global variables.

This article may be helpful: http://www.sitepoint.com/html5-browser-storage-past-present-future/

like image 185
vishnuvp Avatar answered Sep 19 '22 20:09

vishnuvp