Search code examples
javascriptjsonajaxjavascript-objects

JavaScript performance: is it better to use an object variable, or an AJAX request, for large amounts of unchanging data?


So I have a large amount of data, formatted as a JavaScript object, that my website needs access to. Because this data will not be updated, I have two options: create a JavaScript file and paste in the data as a variable. Or, I can upload the data as a JSON file, and then use an Ajax request to get the data and parse it into an object.

Here's some code to demonstrate what I mean.

Option 1 (save data as a JS object variable in a separate JS file):

File object.js

let myData = {
    "1": "A",
    "2": "B",
    "3": "C",
    "4": "D",
    "5": "etc..."
};

...And so on, except my data is very large, so this file ends up being 25,000+ lines.

And I use the variable like this in some script.js

let myVar5 = myData["5"];



Option 2 (save data as JSON, do Ajax magic, and parse into JS object)

file object.json

{
    "1": "A",
    "2": "B",
    "3": "C",
    "4": "D",
    "5": "etc..."
}

And then in my script.js I do this:

let url = "/data/object.json";
$.getJSON(url, function(response) {
    let data = JSON.parse(response);
    let myVar5 = data["5"]
}

Which option would have better performance, in terms of memory, speed, storage, and other practical stuff for websites on the internet?


Solution

  • Which option would have better performance, in terms of memory, ...

    The JSON variant is 7 bytes shorter

    ... speed, ...

    If you don't need the JSON to render the page for the first time, loading it afterwards from a JSON file will be better as it gets loaded after the page rendered, also parsing JSON is probably faster as JS is much more complicated to parse (but were probably talking about nanoseconds).

    ... storage, ...

    not sure how that differs from memory. Maybe both files get cached, maybe not, that depends on the browser etc.

    ... and other practical stuff for websites on the internet?

    I wouldn't go with the hardcoded variant as my IDE would try to parse the file to hint me about its types and properties, which will slow down my development process. It doesnt parse files loaded externally.