So I am trying to understand why my code that stringify an object is much slower then JSON.stringify.
I cant think of a reason for this.
could someone share why this is hapning.
here is my test code that I wrote.
let data = {
name: "test",
id: 3,
hidden: false,
children: []
};
for (let i = 0; i < 7000; i++)
data.children.push({ text: "gh", value: "gg" });
let name = null;
let start = t => {
name = t;
console.time(t);
};
let end = () => {
console.timeEnd(name);
};
const ptype = {
number: true,
boolean: true
};
const stype = {
string: true,
function: true,
date: true
};
const alltypes = { ...ptype, ...stype };
let stringify = json => {
if (json === null || json === undefined)
return undefined;
let str = "";
let type = typeof json;
if (type === "object" && Array.isArray(json)) {
str += "[";
let c = "";
for (let item of json) {
str += c + stringify(item);
if (c === "") c = ",";
}
str += "]";
return str;
}
if (alltypes[type]) {
if (ptype[type]) return json;
return `\"${json}\"`;
} else {
str += "{";
let c = "";
for (let key in json) {
str += `${c}\"${key}\":${stringify(
json[key]
)}`;
if (c === "") c = ",";
}
str += "}";
}
return str;
};
start("JSON.parse");
let jsond = JSON.stringify(data);
end();
start("my stringify");
let myd = stringify(data);
end();