Last active
August 29, 2015 14:19
-
-
Save asalant/6dc3c15ee6a20d44db1f to your computer and use it in GitHub Desktop.
JSON Date reviver performance investigation
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
isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/ | |
isIsoDate = (value) -> | |
return value unless typeof(value) is 'string' | |
isoDateRegex.test(value) | |
isIsoDateOptimized = (value) -> | |
return value unless typeof(value) is 'string' | |
return value unless value.length is 24 | |
isoDateRegex.test(value) | |
dateReviver = (dateTestFn) -> | |
(key, value) -> | |
return value unless dateTestFn(value) | |
return new Date(value) | |
data = for i in [1..10000] | |
date1: new Date(Date.now() + i * 1000) | |
number: 1 | |
string1: "Hello there" | |
string2: "Here's a slightly longer string." | |
obj: { a: 1, b: "2", c: '3'} | |
json = JSON.stringify(data) | |
startAt = Date.now() | |
JSON.parse(json) for i in [1..10] | |
console.log "No reviver: #{Date.now() - startAt}ms"#, parsed | |
startAt = Date.now() | |
JSON.parse(json, dateReviver(isIsoDate)) for i in [1..10] | |
console.log "Regex reviver: #{Date.now() - startAt}ms"#, parsed | |
startAt = Date.now() | |
JSON.parse(json, dateReviver(isIsoDateOptimized)) for i in [1..10] | |
console.log "Regex reviver optimized: #{Date.now() - startAt}ms"#, parsed |
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
No reviver: 148ms | |
Regex reviver: 633ms | |
Regex reviver optimized: 917ms | |
Surprising to see that the additional length check in isIsoDateOptimized | |
actually slows this down. The regex engine in node must be doing this | |
kind of optimization already faster than JavaScript. | |
Some of the time here is spent in new Date(). If we assume that consuming | |
code of the parsed JSON would be doing that conversion of string to Date | |
also, we should get rid of it in this test. Changing lines 16-17 to just | |
`return value` results in the following: | |
No reviver: 179ms | |
Regex reviver: 284ms | |
Regex reviver optimized: 258ms | |
So most of the time is spent actually converting the string to Date, not | |
checking to see if it looks like a Date. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment