Skip to content

Instantly share code, notes, and snippets.

@ngerritsen
Last active October 24, 2017 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngerritsen/20b4cfb553a902049660ca17d45590ff to your computer and use it in GitHub Desktop.
Save ngerritsen/20b4cfb553a902049660ca17d45590ff to your computer and use it in GitHub Desktop.
Template string vs JSON.stringify test
'use strict';
const NS_PER_SEC = 1e9;
const MS_PER_NS = 1e6;
const ITEMS = 100000;
const data = getData();
run();
runWithTemplate();
function run() {
const timer = getTimer();
data.map(item => JSON.stringify(item));
console.log(`Without template took ${timer.elapsed()}ms`);
}
function runWithTemplate() {
const timer = getTimer();
data.map(item => `{
"id": ${item.id},
"username": "${item.username}",
"age": ${item.age},
"stats": {
"friends": ${item.stats.friends},
"posts": ${item.stats.posts},
}
}`);
console.log(`With template took ${timer.elapsed()}ms`);
}
function getTimer() {
const time = process.hrtime();
return {
elapsed() {
const [seconds, nanoseconds] = process.hrtime(time);
return ((seconds * NS_PER_SEC) + nanoseconds) / MS_PER_NS;
}
}
}
function getData() {
const data = [];
for (let i = 0; i < ITEMS; i++) {
data.push({
id: Math.random(),
username: 'John Doe',
age: 29,
stats: {
friends: 3,
posts: 203
}
});
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment