Last active
October 24, 2017 19:43
-
-
Save ngerritsen/20b4cfb553a902049660ca17d45590ff to your computer and use it in GitHub Desktop.
Template string vs JSON.stringify test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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