Тёмный

Faster apps with JSON.parse (Chrome Dev Summit 2019) 

Chrome for Developers
Подписаться 759 тыс.
Просмотров 312 тыс.
50% 1

Because the JSON grammar is much simpler than JavaScript’s grammar, JSON can be parsed more efficiently than JavaScript. This knowledge can be applied to improve start-up performance for web apps that ship large JSON-like configuration object literals (such as inline Redux stores).
Presented by: Mathias Bynens - goo.gle/2Oh2tq6
More info → goo.gle/33czWGH
#ChromeDevSummit All Sessions → goo.gle/CDS19
Subscribe to Google Chrome Developers → goo.gle/Chrome...
Event photos → goo.gle/CDS19P...
event: Chrome Dev Summit 2019; re_ty: Publish; product: Chrome - General; fullname: Mathias Bynens;

Опубликовано:

 

16 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 375   
@programaths
@programaths 4 года назад
Incidentally explains what are context free grammars and why they are faster to parse :-) Don't understand why it's down-voted: 100% knowledge & technical.
@sanderd17
@sanderd17 4 года назад
Never realised JSON is such a nice example of a CFL. When I learned about CFL, the web was still XML driven, and we didn't really treat JSON. When I now have a problem, I always check if it's a regular language or not. But I totally forgot about context free languages. Thanks for the insight.
@movax20h
@movax20h 4 года назад
@@sanderd17 JSON and XML are not regular languages.
@movax20h
@movax20h 4 года назад
@@sanderd17 json is context free. The problem with xml is that it requires closing tags to match the opening ones. If you know all possible tags in advance then it is cfl. Otherwise it is not per se. They are simply not regular languages.
@dimkir100
@dimkir100 4 года назад
I've been curious about the origin of mysterious downvotes for quite a while by now. My hypothesis is: some come from tapping on mobile/tablet on the wrong icon (upvote and downvote are very close to each other and there's a probability of user unintentionally clicking downvote). And another source of downvotes may be when they vote not for the video content, but rather "vote for whether search returned result which matched their request, or returned result they didn't expect". (ie. they wanted quick TLDR tutorial about using JSON.parse, but got video about CFG ...)
@CaptainWumbo
@CaptainWumbo 4 года назад
3.1k up to 36 down as of this comment. Not sure what you're seeing, that looks overwhelmingly positive to me.
@benevans1377
@benevans1377 4 года назад
is this why you guys steal all of my RAM
@Wikmeister007
@Wikmeister007 4 года назад
:'D ...this comment!!
@creayt
@creayt 4 года назад
HAHAHHAAHHA
@prempink12311
@prempink12311 4 года назад
really for me, firefox steals RAM
@creayt
@creayt 4 года назад
Prem Kumar why use Firefox in 2019?
@prempink12311
@prempink12311 4 года назад
@@creayt agreed
@SergioPenafiel
@SergioPenafiel 2 года назад
This is great for a computer theory class. JSON is a context-free grammar while JS objects are not and that pretty much explains the optimization as well
@jonroig8751
@jonroig8751 4 года назад
Interesting. Totally makes sense... I remember reading this awhile ago but didn’t understand why.
@asgp.5327
@asgp.5327 4 года назад
That was a good chunk of info for a 6-minute video. Well done!
@JoeWong81
@JoeWong81 4 года назад
Thanks for that short but extremely helpful tip!!
@vokhshed1886
@vokhshed1886 4 года назад
The speedup seems to be insignificant in spidermonkey, is this because the JSON parser in spidermonkey is slower or because the JS literals are faster?
@romanpoliakov74
@romanpoliakov74 4 года назад
If your web app requires 8MB of json for *initial* load of the page then you're doing something wrong.
@avi150
@avi150 4 года назад
They use 8MB as an exaggerated scenario for benchmarking, obviously that's now how people make real apps. To use small payloads would make it hard to discern performance differences.
@Guztav1337
@Guztav1337 4 года назад
I have seen some really bad cases before. Well those people don't watch this anyway...
@mothutheslow3955
@mothutheslow3955 4 года назад
Hmm, RU-vid requires 2MB. I'd say it depends on the app you are building, if you are handling a lot of meaningful data then you can easily reach 40MB (that you later cache and reuse).
@DarioColetto
@DarioColetto 4 года назад
Where "something wrong" is "using js"
@DarioColetto
@DarioColetto 4 года назад
I know it's a parser "problem", and generally an interpreted langugages "problem". Still :)
@someguyO2W
@someguyO2W 4 года назад
Every day, Javascript finds another way to make me sick.
@TomasKonrady
@TomasKonrady 4 года назад
why? this is logical if you know how parsers works
@someguyO2W
@someguyO2W 4 года назад
@@TomasKonrady it's logical. I agree. But still not intuitive. Most would expect the actual language constructs to be faster. But i guess as explained Javascript just has so many constructs that it can't parse things easily.
@metadaat5791
@metadaat5791 4 года назад
@@someguyO2W No, this is the case for any parser of just about any programming language. It's just that Javascript always gets parsed just before execution, so the parsing time counts towards the execution time. This goes just as much for other interpreted languages like Python or Ruby. And just the same, if you're going to load a large chunk of data in Python or Ruby, you're also not including it as a static literal definition in the source, but also loading it from data. Javascript just has the "tradition" of including large chunks of data as code literals, and yeah it makes sense that if those get large you need a smarter way to load the data.
@someguyO2W
@someguyO2W 4 года назад
@@metadaat5791 yeah, but python has no (or less) ambiguity when it encounters a literal data structure. It knows what to expect. Won't perform much differently from a runtime parser which would do the same thing. As they explained when parsing actual js code, the parser doesn't know its a data structure and thus can't optimize for it. But Json.parse does and that's why it's better. In short, the lack of need for context.
@georgiiperepechko9321
@georgiiperepechko9321 4 года назад
​@@someguyO2W is this the same Python that uses the same braces for both dictionaries and sets? :-) I mean I actually agree that Python is less ambiguous but both languages were built for ease of use first and performance second so I'd say as long as it is readable for humans and makes programmer's life just a bit easier, a bit of ambiguity is fine by me.
@ToddHowardWithAGun
@ToddHowardWithAGun 4 года назад
Serializing an object into a string and parsing it back into an object is faster than just passing the object. Gotta love js.
@neloka4313
@neloka4313 4 года назад
No that's not what this is all about. "{}" isn't "serializing an object into a string", it's a string containing a JSON encoded empty javascript object, serializing an object into a string would mean doing JSON.stringify(obj) and, of course, JSON.parse(JSON.stringify(obj)) is obviously slower than just obj itself.
@morezco
@morezco 4 года назад
oh wow. Woulda never have guessed that
@Mitsunee_
@Mitsunee_ 4 года назад
I'm actually somewhat accidentally using this in a Pokemon Damage Calculator. I have a 33.8 KB json file with all the pokemon data needed. I could probably include the type matchup lookup in that as well.
@hamadrehman853
@hamadrehman853 4 года назад
link to your app please ?
@k_e_n_n_y_mccormick
@k_e_n_n_y_mccormick 4 года назад
the effect is negligible for a project of your size.
@brymstoner
@brymstoner 4 года назад
I've been doing this since Jan 2018. I fetch web page data as json, parse it, and spit it out through template literals.
@GaneshMKarhale
@GaneshMKarhale 4 года назад
super
@cristianouzumaki2455
@cristianouzumaki2455 4 года назад
Subscribing to these channel and watching just 4 of its videos has made that time so much more productive.
@BenRangel
@BenRangel 4 года назад
Surprising, but makes a lot of sense when you considered how a parser works.
@mathematicalninja2756
@mathematicalninja2756 4 года назад
Ah, reminds me of context free grammar :D
@RobGregory
@RobGregory 4 года назад
Good tip and explanation makes sense. Thanks
@MaciejMortek
@MaciejMortek 4 года назад
And after a crazy years of many JS frameworks we are going back again, to a recommendation from Google, to use Server Side Rendering :D :D
@GameFuMaster
@GameFuMaster 4 года назад
which can also involve JS frameworks?
@ianldgs
@ianldgs 4 года назад
It's more complex than that. SSR is only recommended on the initial render. Then the framework you use, like react, has to reconcile the HTML the back-end generated with the data that it used. If everything goes well, the front-end can start rendering stuff on top of that when the user interacts or when data is loaded via XHR.
@exactzero
@exactzero 4 года назад
@@GameFuMaster But not JUST js at least
@XenonG
@XenonG 4 года назад
This one weird trick will...
@GameFuMaster
@GameFuMaster 4 года назад
the intricacies of javascript.
@myview9923
@myview9923 4 года назад
Giving numbers with details maybe helpful instead of just saying 1.5x and 2x. (Smaller time intervals like 0.001ms and 0.005ms isn't much of a difference but the times values will be larger)
@jayit6851
@jayit6851 4 года назад
On their own no, but you have to realize specific intervals don't carry much information. 0.0005ms is short in one instance but over time or in scaling applications that adds up. A specific time interval means nothing without the context behind it while a general relative number can be applied to any case.
@thesilph
@thesilph 4 года назад
if you follow the link at the end you have the numbers and pc specs, etc.
@444haluk
@444haluk 4 года назад
I like how they always use 42 (The Hitchhiker's Guide to the Galaxy) and 1337 (Elite) in examples :D
@johnsonmcbig9157
@johnsonmcbig9157 4 года назад
It'd be nice to see code compression tools utilize this.
@007order007
@007order007 4 года назад
Johnson McBig well if you serialize it to a string it significantly increases the size, which goes completely against what compression tools are for
@CallumCarmicheal
@CallumCarmicheal 4 года назад
@@007order007 var x = {x:2,y:[23,45,{a:4}}; Vs var x = JSON.parse('{"x":2,"y":[23,45,{"a":r}]}'); The additional quotes add 2 characters per object / value with a key. {x:2,y:[23,45,{a:4}} {"x":2,"y":[23,45,{"a":r}]} Even on simple objects with 10 or more members that increases the size a solid bit. Could you imagine large chunks?
@CaptainWumbo
@CaptainWumbo 4 года назад
007order007 In my opinion compression is often used to speed up page load by reducing download time, not really to save disc space. Since users already cache files you would probably see a decent benefit to this, although there may be some cases you want to configure it to prefer smaller file size.
@dealloc
@dealloc 4 года назад
I don't believe this is a type of compression, more a kind of optimization. The thing to keep in mind, though, is that this kind of optimization only makes sense in cases where you have large objects that needs to be parsed. If your application feels slow upon initialization, JSON.parse can be used to defer the parsing of those objects after initialization. But it does still need the similar amount of time to parse the JSON when JSON.parse is called, it's just that it happens when being interpreted.
@mathiasbynens
@mathiasbynens 4 года назад
@@CallumCarmicheal With gzip/brotli, the size difference is often negligible.
@dream_emulator
@dream_emulator 4 года назад
Good tip. Correct me if I'm seeing, but most of the time you will be fetching data from an API as a string (not sure about GraphQL) and parsing the returned string, so everyone is already using this tip I think. 🤔 Also aside from that I can't imagine people stringifying, passing the string as a parameter and then parsing out the objects functions or props is faster than just passing the object. Thanks for the tip though 🤓👍
@joseromualdo97
@joseromualdo97 4 года назад
I think the "stringify" step should be done during the bundling of your app not in the final app source code since the argument of JSON.stringify() is an object and then javascript engine should parse it first in order to pass it to the function. And therefore it would make the app much slower.
@exactzero
@exactzero 4 года назад
I believe the video's about the initial application serve wherein the whole bundle is served, parsed, compiled and executed which adds up to the Time of Interaction. So it's better to serve the UI with JSON string first then parse it later and update UI right after so as to not block the rendering of the interface.
@lukask969
@lukask969 4 года назад
Wonder, if angular 2+ is already buried if google itself talks about react and redux.. maybe i have to rethink my decision to work with angular 8 on my new project.
@derSchnaps
@derSchnaps 4 года назад
I tried to benchmark your examples in chrome console. It always shows that JS way is faster than JSON's one. What is wrong in my benchmark approach? JSON code console.time('test JSON'); var data_JSON = JSON.parse('{"foo":42,"bar":1337}'); // 🚀 console.timeEnd('test JSON'); JS code console.time('test JS'); var data_JS = { foo: 42, bar: 1337 }; // 🐌 console.timeEnd('test JS'); These 2 code pieces were always ran separately
@grumd0
@grumd0 4 года назад
JSON.parse is only faster if your object is veeery big, like 1kb+
@derSchnaps
@derSchnaps 4 года назад
​@@grumd0 Thanks for clarification. I was confused by examples provided by link from description - More info: goo.gle/33czWGH Both examples miss three dots in the end. It literally says `var data_JSON = JSON.parse('{"foo":42,"bar":1337}');` is faster then `var data_JS = { foo: 42, bar: 1337 }`. In video there are tree dots. But anyway it would be important to mention in the video that this trick doesn't work with small objects and explain why. Because the explanation provided in the video doesn't explain why it doesn't work on small scales.
@dankhnw8
@dankhnw8 4 года назад
That was very insightful, thank you!
@wizerd432
@wizerd432 4 года назад
foo: 42 bar: 1337 I see what you did there~
@karthikthakur5221
@karthikthakur5221 4 года назад
What happened?
@metadaat5791
@metadaat5791 4 года назад
@@karthikthakur5221 metasyntactic variables happened
@jakubwegrzyn3798
@jakubwegrzyn3798 4 года назад
Does/will typescript compiler automatically convert bigger objects to JSON.parse call?
@dealloc
@dealloc 4 года назад
No, but TypeScript supports custom transforms (programmatically, not configurable in tsconfig.json), so it would be possible to make a transform that does this.
@TobySug
@TobySug 4 года назад
I think webpack might.
@dealloc
@dealloc 4 года назад
@@TobySug Yes Webpack does through loaders, but I think Jakub meant the TypeScript compiler directly :-) It would absolutely be easier to configure it for webpack, babel, parcel or rollup :)
@rahulxcr
@rahulxcr 4 года назад
Thanks for the tip. Really helpful 👍
@ChrisWalshZX
@ChrisWalshZX 4 года назад
Wow. I would never have guessed that! :-)
@吴迪-x4d
@吴迪-x4d 4 года назад
I wonder which app needs 8MB of json data in a js file.
@JIJzerman
@JIJzerman 4 года назад
I believe Chrome caches a parsed version of a JS file. I guess this means that the object literal version will only need to be parsed once, not on subsequent pages that also use the - cached - JS file. Since JSON.parse() is a runtime function call I guess it will have to be executed on every page where the JS file is used. Is this correct? If so I assume JSON.parse() is faster on the first page, but slower in a whole session (on a multi page site).
@shalomdahal6361
@shalomdahal6361 4 года назад
Can someone please explain this to me:- isnt all the data we receive from RESTFUL API in a string ? so when we do JSON.parse() we are following best practices ?
@LocherYT
@LocherYT 4 года назад
Thanks, my object literals waere like 130kb. Now I know that there are better ways to handle that.
@s_b156
@s_b156 4 года назад
When will google earth be available on a trustworthy browser?
@doug2279
@doug2279 4 года назад
would have been better if you showed a typical use-case you could have refactored from objects to json strings
@amitjoshi956
@amitjoshi956 4 года назад
Thanks a lot, it was very informative 😇
@stevemasters3383
@stevemasters3383 4 года назад
I stock to server side rendering
@programaths
@programaths 4 года назад
I render stocks server side
@exactzero
@exactzero 4 года назад
Stuck? Learn client side!
@ahmde
@ahmde 4 года назад
Thank you for Promise.any() Mathias.
@warpmonkey
@warpmonkey 4 года назад
Does this apply to the parsing of JSON payloads from REST endpoints? Would it be better to return a .js file that is executed at the client with a JSON.parse rather than returning a JSON payload that is consumed by the UI? Or is that communication not affected by this parsing issue?
4 года назад
Great question!
4 года назад
I guess the network Json is already parsed with the json.parse
@yusong-hsu
@yusong-hsu 4 года назад
I’m interest too, and also wonder is anyone use this weird tip on product? 🤔
@mathiasbynens
@mathiasbynens 4 года назад
JSON payloads are by definition not JavaScript. They don't hit the JavaScript parser at all.
@ionelcucu
@ionelcucu 4 года назад
Generally REST APIs return data as "application/json", which means, it's already a JSON. You may use the response object directly in your code after the request is completed just because something else is parsing the JSON for you (angular framework, axios). So, you ALWAYS parse the JSON that comes from REST APIs unless it's a JSONP which has to be executed.
@ultralooter
@ultralooter 4 года назад
Foo: 69, Bar: 420, Fubar: 1337
@ultraviolet.catastrophe
@ultraviolet.catastrophe 4 года назад
Just tested it. This is even faster!
@imvdesign
@imvdesign 4 года назад
It's good , but correct me if I'm seeing, but most of the time you will be fetching data from an API as a string (not sure about GraphQL) and parsing the returned string, so everyone is already using this tip I think. Also aside from that I can't imagine people stringifying, passing the string as a parameter and then parsing out the objects functions or props is faster than just passing the object. Thanks for the tip though
@LugnutsK
@LugnutsK 4 года назад
Your first half is right, rest api etc return Jason strings which are parsed using JSON.parse. Second half, there is no reason to stringify an object after you already have it. The speedup is at parsing time-when the .js file gets read by the browser. Once the JavaScript is actually running then parsing is already done.
@nishkalkashyap2906
@nishkalkashyap2906 4 года назад
Thank a lot for the information. I'm still not going to use this :)
@gauravsharma354
@gauravsharma354 4 года назад
Does this means the extra bundle size (leading to slowness of first rendering) because of shipping JSON instead of JS Objects ?
@psyneur9182
@psyneur9182 4 года назад
This is probably a case-by-case thing. How switching to JSON affects the time to first render (I'd guess) varies a lot based on the website. Some websites' user bases might have slower internet connections, so shaving off a couple hundred bytes could save more time than JSON saves. Other websites may have users with generally much faster internet connections where a couple hundred bytes don't matter (especially considering many websites surpass 1 MB in size...). My personal opinion on this is there are usually other ways to improve load times that you should probably worry about before doing this.
@BruceArmstrong09121997
@BruceArmstrong09121997 4 года назад
Eye opening!!
@eminem2
@eminem2 4 года назад
SO WHY THEN doesn't V8 do this behind the scenes?
@MundoFinky
@MundoFinky 4 года назад
Because it can't know if the object can be serialized to json without analising it...
@Maric18
@Maric18 4 года назад
why would a web page need 10kb of javascript object on initial load? i mean you know its ok to dynamically load stuff, right? the initial website should be INSTANTLY there and once it shows, you should go and fetch stuff in the background. the 800 ms until the user clicks something is cheaper than 800ms before the user sees anything. Just have proper placeholders/openable stuff to hide the loading and maybe a spinner.
@yashasvi9655
@yashasvi9655 4 года назад
I hated Grammars as a subject in my Engineering. Context-Sensitive grammar was beyond my puny head
@Keno_jm
@Keno_jm 4 года назад
Does Create React App have this optimization applied already?
@cutevegan7163
@cutevegan7163 3 года назад
But you guys probably parse lots of ads. Instead of doing micro optimization why not ban ads that will probably make browser faster by 80%
@semproser19
@semproser19 4 года назад
I always test this kind of thing, and I'm not getting any positive results at all. On smaller objects it's 20 times slower to parse, at objects over 10KB it's still 6 times slower to parse. Testing just an object with any kind of data in it vs the same object in string form. I built a jsfiddle (code sandbox) to test it. Code: /wLq063h1/3/ Just plop that at the end of the jsfiddle url to get the code and test it for yourself. Running one object 50,000 times: 1700ms for parse, 250ms for literal on a 13KB object. Have I missed something major or is this only useful when your object is several MB large (in which case what the heck are you doing loading MB of data on startup?)
@LukaLightBringer
@LukaLightBringer 4 года назад
That doesn't actually test this, the parsing of the AST for your data objects in your testObj function happens at compile time, so before you start your timer, ie. you're not actually comparing the entire cost of the data representation in both cases.
@drevartan4958
@drevartan4958 4 года назад
​@@LukaLightBringer Does that mean, in a situation like this, that the object literal is only parsed once (at compile time), where the JSON.parse is evaluated at each iteration of the loop? Wouldn't that mean that in a situation like this, where the object is declared multiple times during its run, it would be faster to use object literals?
@LukaLightBringer
@LukaLightBringer 4 года назад
@@drevartan4958 correct, if you need several distinct instances of an identical object don't use the JSON approach, if it doesn't matter if they are distinct hoist it
@semproser19
@semproser19 4 года назад
@@LukaLightBringer interesting theory, would you mind rewriting the sandbox example so it does actually make the object each time?
@LukaLightBringer
@LukaLightBringer 4 года назад
@@semproser19 It's not easy to write a test for it but I've managed to implement one in a NodeJS environment, you can find it on repl it /repls/SandybrownExcitingQbasic this test is by no means perfect. There is some pollution in the timed interval for the test, but its the same for both cases, this means the result becomes clearer the larger you make the test object since it will start drowning out the pollution. But it should still be indicative with the object you had used in your test, I've used the same.
@TheNewton
@TheNewton 4 года назад
NEAT 🌟! the parsing explanation is very clear thanks, bookmarked🔖 this to integrate into workflow and coding👨‍💻
@renixmar3373
@renixmar3373 4 года назад
Okay, but what about pre defining the variable as an object then
@sleepysonic
@sleepysonic 4 года назад
I actually use a 100MB json file in a project atm (lots of 7kb base 64 images put the size up)... only takes 1.5 seconds to load which honestly is so much quicker than I thought it would. I guess maybe that's thanks to the way JSON.parse works.
@thalibmuhammad9519
@thalibmuhammad9519 2 года назад
content!!!!!
@sonyarianto
@sonyarianto 3 года назад
nice tips
@pranjalagnihotri6072
@pranjalagnihotri6072 4 года назад
So should we store our redux state as string and parse it everytime when we read it?
@squ94wk
@squ94wk 4 года назад
Would be funny, if it wasn't missing the point.
@exactzero
@exactzero 4 года назад
Yes if you didn't watch the video.
@pranjalagnihotri6072
@pranjalagnihotri6072 4 года назад
I missed that webpack part, as he said we don't need to do this manually webpack will take care. So it's good
@ManasTunga
@ManasTunga 4 года назад
does it mean for deep clone json.parse(jaon.stringify({})) is faster than doing it by any library
@Mishiman
@Mishiman 4 года назад
Yes, it's also the easiest method
@sazma
@sazma 4 года назад
Is this true in Firefox as well?
@dammyammy
@dammyammy 4 года назад
Cool trick
@jeremyleeshields9721
@jeremyleeshields9721 4 года назад
"Server side rendering" This is PHP
@jeremyleeshields9721
@jeremyleeshields9721 4 года назад
@@blazingelse9104 Theres nothing wrong with it, its just this is presented like some insane innovative idea, where it is not
@dragonflyK110
@dragonflyK110 4 года назад
@@jeremyleeshields9721 I didn't get that impression at all, it was simply mentioned as one possible solution, nothing more. Would you have preferred that they did not mention it at all?
@alb12345672
@alb12345672 4 года назад
@@blazingelse9104 Very Important for search engines, since an SPAs HTML is garbage.
@alb12345672
@alb12345672 4 года назад
@@blazingelse9104 My Vue.js apps (I didn't dig deeper into this though, they are internal and not visible to search engines, so SEO isn't an issue) have a 20 line HTML payload with a sorry message if JS isn't available. I don't know if google executes the JS on the page in a non-visual container. Sure, if you inspect the document in the browser, you see everything wrapped in multiple data-v-UUID.substring(-6) attributes. As devs we care about the HTML, but maybe .01% of consumers will ever give it a second look :lol:.
@ishdx9374
@ishdx9374 4 года назад
heads up, node.js is faster performance wise than php for server side
@TheNewton
@TheNewton 4 года назад
6:21 Referenced V8 Blog - The cost of JavaScript in 2019 v8.dev/blog/cost-of-javascript-2019
@TonyWinston57
@TonyWinston57 4 года назад
What are the long term effects for Mobile Video
@narucy56
@narucy56 4 года назад
Feels bad. Web should allowed to run AOT-compiled code.
@twitchizle
@twitchizle 4 года назад
JSON.parse("oh i see")
@arshiaalidosti8818
@arshiaalidosti8818 4 года назад
Wow ! Tnx !
@fashnek
@fashnek 4 года назад
Is this in Closure Compiler?
@berndeckenfels
@berndeckenfels 4 года назад
The optimized parsing should also happen for XHR, right?
@limerarysun
@limerarysun 4 года назад
Awesome
@foljs5858
@foljs5858 4 года назад
Why not add a Literal({}) primitive in Javascript that serves as a marker to the parser that "what's inside is a JSON-like literal"?
@ericmarcelino4381
@ericmarcelino4381 4 года назад
We already have Object
@faisalhakim5920
@faisalhakim5920 4 года назад
there is no point of adding that, the functionality is the same as JSON.parse anyway.
@dealloc
@dealloc 4 года назад
Remember, it is only beneficial for _initialization_ of the (large) object, not the parsing itself. Both the parsing of the object and JSON.parse needs to be parsed at some point. The idea is just to make the code run parse the least amount of tokens-string is a single token, whereas an object can be a multitude of tokens-before running the code (TTI), and then calling JSON.parse to parse again the contents of the string.
@kiontupper
@kiontupper 4 года назад
@@ericmarcelino4381 But "Object" is just a constructor. It doesn't change the way the syntax is parsed. "x = new Object({/*...*/})" is just as bad as "x = {/*...*/};". To actually optimize this you'd have to add a new keyword to the grammar that somehow indicates "this is a JSON literal." That would also require browser support and cross compilers like babel would have to remove it to support older browsers anyway, unless it was in a comment. For example "x = /*strict*/ {a: b}" could work if browsers recognized /*strict*/ as a prefix for a JSON literal and older browsers would just ignore it and parse it normally without the perf benefit.
@georgebateman3876
@georgebateman3876 4 года назад
​@@kiontupper It seems unlikely that many people hand-edit really huge single javascript objects, so this proposed new syntax doesn't have to be user-friendly, as the objects will all be autogenerated. So the syntax JSON.parse('') is already a good enough answer to this problem and something entirely new like "x = /*strict*/ {a: b}" isn't really needed. Perhaps JS parsers should specifically look for code like JSON.parse('') and treat it specially for the highest possible speed, but that should be enough.
@fabiodan30
@fabiodan30 4 года назад
Looks like something Terser could do!
@-leovinci
@-leovinci 4 года назад
What’s the codes’ font name? It looks cooler than my usually used Consolas?
@SoyJayP
@SoyJayP 4 года назад
Wow
@saadatbaig
@saadatbaig 4 года назад
Assuming for legal reasons foo is 42 and not 420 lmao
@Mr.Andrew.
@Mr.Andrew. 4 года назад
Wouldn't parsing text instead of instanciating an object always be faster in any programming language?
@Ian-hj8qk
@Ian-hj8qk 4 года назад
Andrew F I believe the reason why it’s faster in JavaScript is because it’s an interpreted language rather than a compiled language. Basically what this video explains is that the JavaScript engine needs to go through each property of a JSON object to ensure its itemizing and indexing the Object correctly. Using JSON.parse simplifies the work the JavaScript interpreter needs to do, and offsets the responsibility to the JSON.parse interpreter which is much simpler. In compiled languages however Objects are being compiled directly to machine code (and thus memory) rather than going through an interpreter that transpiles to a language that is later compiled to machine code.
@soranuareane
@soranuareane 4 года назад
For compiled languages no. For interpreted languages yes and for the same reasons mentioned in the video. For compiled languages, using an equivalent to JSON.parse defers the object parsing to runtime, while having an object literal (or equivalent thereof) evaluates it at compile-time. You can test this in your favorite compiled language with object literals.
@JivanPal
@JivanPal 4 года назад
@Andrew F, it's not a matter of parsing text vs instantiating an object; it's a matter of parsing a JSON string using JSON.parse() vs. parsing a JS object literal using a JS engine. The browser has to do one or the other, and both are parsing actions, but JSON is a subset of JS, and also a CFG, so using it as described in the video yields the results you see.
@MrTyler918273
@MrTyler918273 4 года назад
@@JivanPal Yes this is the real reason. Its effectively the difference in efficiency of JSON.parse('{"foo":42,"bar":1337}') vs eval('({"foo":42,"bar":1337})'); they return the same thing but its no surprise that eval is slower since it has to handle a lot more potential cases (particularly context sensitive ones) than JSON.parse does.
@frigga
@frigga 4 года назад
From google I would have expected a recommendation for Angular.. ?
@dylam9509
@dylam9509 4 года назад
well, will this trick work with a valid JSON object literal where the keys are already denoted in strings?
@mathiasbynens
@mathiasbynens 4 года назад
It only works for JSON.parse, not for object literals (no matter whether the object literal has quotes around its keys).
@dylam9509
@dylam9509 4 года назад
@@mathiasbynens how big should the object be to see JSON.parse run faster than object literal assignment? thanks
@mathiasbynens
@mathiasbynens 4 года назад
@@dylam9509 The benefits should be visible for anything larger than 1 kB, and significant for anything larger than 10 kB. But as usual in web development: it depends.
@thanatosor
@thanatosor 4 года назад
Something wrong with JS serialized object init
@AprilSKuhn
@AprilSKuhn 4 года назад
parse
@etienne12
@etienne12 4 года назад
The reality is that it is extremely rare for web developers to work with payloads of 8MB on client-side. For a small payload, Json.parse is less efficient, less clean and less easy to maintain. Cool trick, but unusable in practice.
@herohema5
@herohema5 4 года назад
Thank you!
@wassim24
@wassim24 4 года назад
Not always true. In our case for example, we have a generic back-end (sort of a core/kernel), which loads all of an object graph when requesting the data. In this situation, if you are asking for a dozen of objects, you will literally download 3 megabytes json. And in the need (business constraints) to maintain the backend decoupled from any front-end "orginization/logic" i have already dealt with 60Mb plus JSON objects. Integrating GraphQL was an option, but we did not had enough resources to go on that path.
@dealloc
@dealloc 4 года назад
@@wassim24 But async operations (like fetching) happens after initialization. This video explains about initial static objects. Also when you fetch, the API (depending on which API you use) will parse JSON body from a response by itself, so it already uses JSON.parse under the hood. Also if you're working with large JSON objects, it may be more beneficial to stream the data so that you can parse and validate individual chunks, rather than waiting for the whole object.
@mathiasbynens1518
@mathiasbynens1518 4 года назад
The video explains that you ideally wouldn't apply this trick in your source code, since that would indeed increase the maintenance burden. Performing the optimization at build time is the way to go.
@skyleite3016
@skyleite3016 4 года назад
No it isn't. Watch the video
@angelcaru
@angelcaru 4 года назад
I noticed you're a parser for more than a minute
@Defotowe
@Defotowe 4 года назад
Hey Mathias , where is my ram? Just to you know i don't have any more slots to upgrade, so can you be so kind and stop stealing my ram I will go broke if i buy a new pc :(
@AlexanderTrefz
@AlexanderTrefz 2 года назад
I wonder when people will finally stop pretending that Server Side Rendering is somehow faster than a well structured client side app. People have to download all of that HTML and then the browser has to parse it all the same as the JS. There is no speed benefit there, unless your SPA sucked to begin with.
@PauxloE
@PauxloE 4 года назад
I would hope that you don't write that 8 MB Javascript object by hand. And if you generate it on server side, wrapping it into JSON.parse (or just adding the JSON.parse on the client side) should be easy to do.
@elmotareal
@elmotareal 4 года назад
hmm, i wonder how angular cli does it?
@mourkis303
@mourkis303 4 года назад
would like to know too
@ashalshammari
@ashalshammari 4 года назад
Or you can just drop JS and replace it with non-tickey language that is faster to parse, this is the ultimate dream.
@exactzero
@exactzero 4 года назад
Will you do the honors?
@santariopratt4132
@santariopratt4132 3 года назад
Can you do a hack for me it's a game called hasharia drifter its got a json file which we can't mod neon texture onto the car paint can you please help me bro game guardian used to work the developer did something
@NateLevin
@NateLevin 3 года назад
LOOL!
@nnaaaaaa
@nnaaaaaa 4 года назад
example number 521 why developers and end users despise javascript in any form.
@alb12345672
@alb12345672 4 года назад
Why all the gaslighting that it is such a good language? The tooling isn't that great either. Visual Studio 2019 is a mature product with 30 years of heritage.I come from C++/C# and I am working on Vue.js with Javascript and it is really a big step down. They try to patch the language (like let vs var so variables don't float up), but it still sucks. Brokers should be using something like python or ruby. Sucks how Javascript, developed in 1993 by a guy over a few weeks with a deadline, became such a 2 ton elephant.
@p0358
@p0358 4 года назад
@@alb12345672 Python or Ruby? Ewww... I'll stick with JavaScript then
@JivanPal
@JivanPal 4 года назад
@jaff, this has nothing inherently to do with JS, but is simply a consequence of three things: (1) Valid JSON strings are a subset of valid JS object literals (2) Parsing JSON is quicker than parsing JS (3) JS is interpreted rather than compiled. For example, if there was a "CPPON (C++ Object Notation)" language with a context-free grammar, and a `cppon.parse()` function in C++, then the same techniques described in this video could be used to collectively make compilation and execution of a C++ program faster - compilation would be faster, execution would be slower; but collectively, compiling and then executing would take less time.
@nnaaaaaa
@nnaaaaaa 4 года назад
@@JivanPal I understand the how and why extensively, this doesn't make it any more okay, in fact it makes it far worse.
@JivanPal
@JivanPal 4 года назад
@@nnaaaaaa, how so...?
@rajkarthick.t
@rajkarthick.t 4 года назад
Awesome trick. 💥 Sometimes we may encounter circular reference error occurs when you have a property of the object which is the object itself directly (a -> a) or indirectly (a -> b -> a).
@mathiasbynens
@mathiasbynens 4 года назад
This falls under the cases we discuss at the 01:22 mark. Objects with circular references cannot unambiguously be represented in JSON, so this trick won't work for them.
@joydemourir
@joydemourir 4 года назад
Once I JSON.parse() my object, what the hell am I supposed to do with that string??
@dhkatz_
@dhkatz_ 4 года назад
This is for object literals. You provide JSON.parse with the JSON representation of the string. This isn't meant for dynamic data.
@OldAlexCat514
@OldAlexCat514 4 года назад
@@dhkatz_ for what kind of data is it meant then? Thinks!
@ishdx9374
@ishdx9374 4 года назад
@@OldAlexCat514 object data
@ishdx9374
@ishdx9374 4 года назад
@@OldAlexCat514 Its for initial state, further you can add new fields without impact on performance
@MarcusLetric
@MarcusLetric 4 года назад
The only thing I don't get is the reason someone would store large amounts of data in object literals...
@skyleite3016
@skyleite3016 4 года назад
It's common for application state in front end
@MarcusLetric
@MarcusLetric 4 года назад
@@skyleite3016 That's a variable, not a literal...
@skyleite3016
@skyleite3016 4 года назад
@@MarcusLetric No, object literals are used for initial states, especially in something like redux.
@ragnarlothbrok367
@ragnarlothbrok367 4 года назад
Cool.But how to do it on a large objects with multiple lines with mixed datatypes? -.-
@SimonBuchanNz
@SimonBuchanNz 4 года назад
backtick strings, and the second parameter to JSON.parse, but you should probably avoid both if you're concerned about speed and size.
@ragnarlothbrok367
@ragnarlothbrok367 4 года назад
@@SimonBuchanNz Im already using backticks in my data objects for interpolation so I guess I cant use this feature in most resource heavy parts of my projects. And the other con of using JSON in JS is that you basically have to access all the data and rewrite it again even if you want just add one line at the end of it, especially fs.appendFileSync is a misery with JSON.
@mathiasbynens
@mathiasbynens 4 года назад
Same as you would for any other object. Here's an example JavaScript implementation: v8.dev/features/subsume-json#embedding-json-parse
@gamecast4432
@gamecast4432 2 года назад
Browser speedrunning
@grainfrizz
@grainfrizz 4 года назад
Woah
@zlatanonkovic2424
@zlatanonkovic2424 4 года назад
Hi gang!
@nabiisakhanov3522
@nabiisakhanov3522 4 года назад
Did you just call react and redux "frameworks"?
@gcash49
@gcash49 4 года назад
these days frameworks and libraries as terms seem to almost be interchangeable
@nabiisakhanov3522
@nabiisakhanov3522 4 года назад
@@gcash49 well yea, they seem, which doesn't mean they are
@gcash49
@gcash49 4 года назад
@@nabiisakhanov3522 never said they were ;)
@exactzero
@exactzero 4 года назад
This is why we never move forward. We keep arguing over what to call things.
@zoltankurtyak3398
@zoltankurtyak3398 4 года назад
FRAMEWORKS - REACT - REDUX...
@mykhailohostieiev6513
@mykhailohostieiev6513 4 года назад
jQuery...
@neizvestniydrug
@neizvestniydrug 4 года назад
Problems with this method start to show up when your string literal contains some unexpected symbols for some server-json-encode-html-http-json-parse pipe transformations, and you will find yourself making something like JSON.parse('{...}'.replace(' ','\ ')) all over you raw data in your page
@matheworson9669
@matheworson9669 4 года назад
hi gang
@arunachaleshwaran
@arunachaleshwaran 4 года назад
hear I having the feeling... whhhaaaat🙄
Далее
Learn JSON in 10 Minutes
12:00
Просмотров 3,2 млн
Dora was kidnapped and then… 😨 #shorts
00:18
Просмотров 2,4 млн
Sign-in form best practice
20:20
Просмотров 111 тыс.
Is JSON Blazingly Fast or...?
9:57
Просмотров 192 тыс.
10 modern layouts in 1 line of CSS
21:39
Просмотров 1,1 млн
Industrial-scale Web Scraping with AI & Proxy Networks
6:17
Cursor AI tutorial for beginners
40:35
Просмотров 54 тыс.
Command Line Tools ALL Developers Should Know
6:15
Просмотров 108 тыс.
How I Made JavaScript BLAZINGLY FAST
10:10
Просмотров 219 тыс.
7 Amazing Developer Tools that you're not using yet
6:27
Parsing JSON Really Quickly: Lessons Learned
47:52
Просмотров 74 тыс.