Search code examples
javascriptperformancestackheap-memory

global export vs. scoped export


Let's say we have those two similar es-modules:

The first one exports a big static array of e.g. dummy data:

export default const dummyData = [ /* big data set */ ];

The other one exports a function that returns the dummy data:

export default function getDummyData() {
   const dummyData = [ /* big data set */ ];
   return dummyData;
}

Is one approache preferable to the other one e.g. because of memory usage at runtime?


Solution

  • First consider whether the data is actually large enough for the amount of resources it consumes to be worth worrying about. Often times, it isn't; many modern phones and computers are capable of a lot without noticeably impacting the user's experience.

    If the amount of data is large enough to worry about, then: exporting a function will result in the data being put on the heap only on demand, but (your current implementation) will also result in data being created every time the function runs. So

    • If, in many cases, the data never gets requested, it could be better to use a function because then the data doesn't get loaded into memory unnecessarily
    • If multiple other modules use this one, calling the function for each one could be an issue, because then you'd be loading a new deep copy of the data into memory for each call. (This could be mitigated by saving the data into a persistent outer variable the first time the function is called, but that'll also prevent garbage collection.)
    • If the data is always used, and it's only used once, it doesn't matter. May as well export the plain object.

    If this code runs on the frontend, some might consider a nicer approach to be to call an API that returns the data instead of hard-coding it into the source.