2

I have a regular scenario, I'm getting some data from a server then spitting it out with the page for later use, however I'm thinking what would be a better way of storing it.

Usually I would do something like

<script>
    window.myData = <?= json_encode($myBigData) ?>;
</script>

Now I would have my data stored in the window object which I can access later on from my scripts, however isn't that going to take up double the memory? The data will be stored once as text on the page and once as actual data in the DOM, well probably not twice as much but still would take up more memory, right?

Isn't something like this going to be a better alternative

<script>
function getMyData() {
    return <?= json_encode($myBigData) ?>;
}
</script>

This way the data will be stored only as text in the page, then I Will get it once I need it, do some operations with it and JavaScript will GC it once it's done it's business as opposed to the first scenario where it would stay in memory long before I needed it and long after I used it unless I unset it manually.

I want to ask if my logic is correct or that is just some nonsense, is there any actual benefits of doing that?

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144

2 Answers2

0

Never have large objects hanging around in global scope. Uses lots of memory, code is not clean at all. All you can find is cons.

Better store a unique identifier (an id probably?) in Web Storage either Local or Session stores and have a method to retrieve those data from the server when needed. In order to not have the server do the same work over and over again you can cache the response, so whenever you try to fetch data from server you get them from cache, avoiding computation.

From MDN:

sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)

localStorage does the same thing, but persists even when the browser is closed and reopened.

Web Storage API

In which from these front end persistent methods/APIs to store data on front end is up to your needs.

Community
  • 1
  • 1
gdyrrahitis
  • 5,598
  • 3
  • 23
  • 37
0

Have you considered using a technology like AngularJS to present the JSON data in user-readable form? You can use pagination to limit the data represented on screen at any time.

Translating the data en masse back and forth from JSON to text sounds like more trouble that it's worth. If there is (now, or in the future) data that doesn't need to be presented to the user, you would need to find a place for it anyway. And how would the user make small changes, without doing a big process to save the whole thing and then re-convert it to text?

Community
  • 1
  • 1
Tim Grant
  • 3,300
  • 4
  • 23
  • 31