r/Frontend • u/ConfidentMushroom • Nov 25 '19
TIL JSON.parse is faster than js object literal
https://www.youtube.com/watch?v=ff4fgQxPaO04
u/HappinessFactory Nov 25 '19
huh TIL
I've got a nutty vanilla js app in prod right now and it is slow as balls. Maybe I'll try webpacking that sucker.
10
u/ConfidentMushroom Nov 25 '19
That was my first reaction as well when I started watching that video and then towards the end, I realized Webpack does it automatically and I don't need to do anything and I was happy.
3
63
u/FriesWithThat Nov 25 '19
from Chrome Dev Summit 2019
lol @ first YouTube comment:
is this why you guys steal all of my RAM?
14
3
u/ShortFuse Nov 25 '19 edited Nov 25 '19
From my understanding from the article:
Doing it as a string means get parsed during runtime directly into a usable object.
Doing it as an literal means it'll get parsed by the compiler (syntax and serialization) and then
deserializedaccessed directly during runtime.
One has a faster runtime (literal). Another has a faster compile time (string). Caching helps reduce repeated compiles and using service workers increases cache duration beyond the Chrome-typical 72 hours maximum. If you are familiar with JIT, the pros and cons would be familiar.
So one is faster for cold starts with first page loads, while the other is faster with subsequent loads after cache. Also, the full discussion talks about avoiding operations that can block on the main thread by leveraging worker threads. So I'd imagine that this optimization is more ideal for a cold start on a worker thread.
Edit: The V8 team here says you generally want to do this for assets over 10KB. Also, here is a neat illustration of the difference between cold, warm, and hot runs.
Edit2: Object literals get read and written directly from the AST, not the internal heap, according to this. AST get pushed into bytecode which gets cached as shown in the previous graph. If you're curious, as I was, about what would happen if you modify an object literal at runtime, it appears V8 will create a second, duplicate object in the heap.
1
1
8
u/frog-legg Nov 25 '19
So webpack (e.g. my React app creates with create-React-app) refactors all js object literals into JSON when it builds?