Which is the better option?
So I am not sure if there's a big performance difference between using JavaScript instead of JSON for my array filled with data
(Reason I am not using JSON for my big array with data is because I don't know how to setup a usable JSON-file, I tried before but couldn't get my JavaScript-file to use it)
If there is a huge difference in performance and speed, could someone show or tell me how to make a JSON-file that I can use in JavaScript?
I can just create a .JSON in my program (visual studio code) but I don't know how to allow my JavaScript file to run it.
(so in other words, there's an array of 1200 + lines in my javascript and I am wondering if it would hinder the performance and speed)
4 Replies
I don't think there is a huge difference in performance (someone please correct me if I am wrong). Still, I think it would be cleaner to have that much data stored in a separate JSON-file.
One way to do that is to create a .JSON file in VS-code, say you call it data.json. If you want to use it in a JavaScript-file, you can start that file with the line
const myData = require("./data.json");
You should now be able to access any information from the data.json-file using the variable myData in your JavaScript-file.
hold on, so what I should do in my javascript is basically this?
or in which way am I supposed to use the mydata
You don't really write JSON by hand, at least not when it comes down to data. If you currently have an object with all that data what I'd suggest is to simply log it to the console as JSON and copy+paste it to separate file:
console.log(JSON.stringify(data))
.
Is there a huge performance difference? Not really, but you may be loading a big chunk of data in memory for no reason if the people visiting your site never actually need to use that data. Maybe they do, so I guess it depends on what you are trying to do. Still, you're definitely adding tasks for the browser to download and parse until it can run all the code so your SEO will be impacted. Best to have a separate JSON file, since you may actually want to download it separate in teh future, or generate it from another application, source, etc.
In other words, don't treat code as data whenever possible.
To load that JSON you'd make a network request using fetch
to download that resource, parse it with JSON.parse
and use it in your code.Close. It'd be:
If I'm printing JSON for copying with even the remotest possibility I'll need to tweak it, I generally use:
JSON.stringify(data, null, 2)
which will pretty print it with an indentatation of two spaces.