The cost of parsing JSON
v8.dev
v8.dev
maybe I'm being picky though.
Think I'm joking?: https://www.scientificamerican.com/article/not-so-conservati...
Given the choice between a secret fool who has fun, and a joyless thought-policing jerk who happens to be right on an issue, people will choose the fool every time; and frankly I can't blame them.
It always amazes me that people who need so strongly to express their individualism in such ways are willing to tie their own puppet strings and offer to dance to another's will.
relaxes in pure pristine air-shed
A good rule of thumb is to apply this technique for objects of 10 kB or larger — but as always with performance advice, measure the actual impact before making any changes.
Although it may still not be worth it. At work I have this hand-rolled utility for mocking the backend using a .har file(which is a JSON). I use it to reproduce bugs found by the testers, who are kind enough to supply me both with such a file and a screencast.
On a MacBook Pro a 2.6MB .har file takes about 140ms to parse and process.
I worked on an app a while ago which would have to parse 50mb+ JSON objects on mobile devices. In some cases (especially on mid-range and low-end devices) it would hang the main thread for a couple seconds!
So I ended up using a library called oboe.js [1] to incrementally parse the massive JSON blobs putting liberal `setTimeout`'s between each step to avoid hanging the main thread for more than about 200ms at a time.
This meant that it would often take 5x longer to fully parse the JSON blob than just using `JSON.parse`, but it was a much nicer UX as the UI would never hang or freeze during that process (at least perceptively), and the user wasn't waiting on that parsing to happen to use the app, there was still more user-input I needed from them at that time. So even though it would often take 15+ seconds to parse now, the user was often spending 30+ seconds inputting more information, and now the UI would be fluid the whole time.
It is length prefix encoded format so it’s pretty safe to work in a streaming manner too.
https://code.fb.com/android/improving-facebook-s-performance...
side note: legit question, I don't do web/app dev
So even if you put it behind a promise, when that promise actually runs, it will block the thread.
In essence, using promises (or callbacks or timeouts or anything else like that) allows you to delay the thread-blocking, but once the code hits `JSON.parse`, no other javascript will run until it completes. And since no other javascript will run, the UI is entirely unresponsive during that time as well.
[1] Technically there are web-workers, and I looked into them to try and solve this problem. Unfortunately any complex-objects that get sent to or from a worker need to be serialized (no pass-by-reference is allowed except for a very small subset of "C style" arrays called TypedArrays). So while you could technically send the string to a worker and have the worker call `JSON.parse` on it to get an object, when you go to pass that object back the javascript engine will need to do an "implicit" `JSON.stringify` in the worker, then a `JSON.parse` in the main thread. Making it entirely useless for my usecase.
But continuing with that same thought process, I very nearly went for an architecture that used a web-worker, did the `JSON.parse` in the worker, then exposed methods that could be called from the main thread to get small amounts of data out of the worker as needed. Something like `worker.getProperty('foo.bar.baz')` which would only take the parsing hit for very small subsets of the data at a time. But ultimately the oboe.js solution was simpler and faster at runtime.
If you have a large json object. You can use the fetch api to work with it. If you need to cache it, use the cache storage api. Unlike localStorage which will freeze the UI, cache storage wont.
It’s slightly slower since it needs to talk to another thread but who cares as long as the UI is responsive to do other things.
It looks like it doesn't, but the same exact symptoms will happen even while awaiting the fetch json().
http://oboejs.com/examples#demarshalling-json-to-an-oop-mode...
I could see the value in this for sure. I currently have a problem of loading a ton of JS for some users who have thousands of objects embedded in the view with Rails using toJSON() in a <script>. It’s creating far too much weight on the frontend. I’ve been considering fetching it via a simple REST request instead.
I think of js entirely from a node.js perspective where I conceptualize it as an async task. Is this also wrong?
But both server-side and client-side JS use the same system, the event loop. It's basically a message-queue of events that get stacked up, and the JS engine will one at a time grab the oldest event in that queue and process it to completion. Anything "async" will just throw a new event into that queue of events to be processed. The secret sauce is that any IO is done "outside" the JS execution, so other events can be processed while the IO is waiting to complete.
Take a look at this link, or search up the JS event-loop if you want to get a better explanation. It's deceptively simple.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Even...
Yes, node.js javascript runtime is based on V8, the same that runs in Chrome. Javascript is single threaded so anything that is not I/O bound will block the main thread. If you don't want to block the thread becasue you have long running calculation/parsing task, then you can use worker threads[1]. This will run your task in separate thread and not block the main one.
[1] https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads...
It's a really annoying problem, and I'm actually really happy to see that many others have the exact same thoughts I had at the time, and that I wasn't just missing something obvious!
For example: https://github.com/nodejs/node/blob/master/src/node_crypto.c...
I generally use that as an example when explaining to people why Node isn't a great fit for a lot of workloads. They have to use these features internally, but you as the user with a CPU-intensive job don't have access to those features.
[0]: There is now the Web Workers API which does allow you to run code in the background. I've never used it, but I have heard that it has a pretty high overhead since you have to communicate with it through message passing, so it's possible you wouldn't actually gain anything by using it to parse a large JSON object.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers...
I believe you'd use Workers (WebWorkers?) https://developer.mozilla.org/en-US/docs/Web/API/Workers to actually do it off the main thread entirely inside JS.
You could try to use a web worker, but then you run into the problem that they don't have shared memory, so you need to pass data back some other way.
What was the memory overhead for the application?
And I did originally plan on using something like a websocket, but turns out with some minor changes on the server side we could start streaming data while it was still being gathered, and oboe.js is actually able to start parsing data even while it's still downloading from a normal XHR request, and is designed to be as efficient as possible (so it throws away string data as soon as it's not needed any more).
So there weren't really any additional benefits to be had from using websockets and breaking it up into multiple distinct requests would probably have been slower!
(I just realized I forgot to add a link to oboe.js! But I highly recommend it. It seems it's just gotten better since the last time i've used it)
It was a system where the goalposts moved many times during the development. If I were to do it again, I wouldn't use JSON, but after having the goals change a few times and then having the original server-side components get co opted to work on other projects, it was hard to justify the time that would be spent switching to a different, more appropriate wire format.
Example fibonacci worker code that doesn't block the UI, even at larger calculations
const fib = n => (n < 2 ? n : fib(n - 1) + fib(n - 2))
onmessage = msg => {
console.log('fibonacci worker onmessage', msg)
postMessage({ num: msg.data, result: fib(msg.data) })
}
[1] https://github.com/bharathnayak03/react-webworker-hookSo passing a string to a worker and having it JSON.parse it works great. But when you go to pass that object back to the main thread, it implicitly does a JSON.stringify and a JSON.parse back on the main thread (technically it's called a "Structured Copy", but it's mostly the same thing), putting you in the exact same situation.
This whole thread has been really nice to read, because I beat my head against a wall for a long time before I finally found a solution, and I'm glad to read that I wasn't the only one to think this was a lot more deceptively hard than I thought at first thought (or second, or third...)
Why? Because a large JSON structure is most probably just a large JSON structure, but you most probably don't need it as a whole. You may need a total count of items, you may need a paginated set of items, or only a certain item or a set of fields of items — well, an API.
Except funnily enough JSON.stringify + JSON.parse is usually recommendation as it's either comparable or faster than the structured copy the engine itself does :/
Web workers are depressingly bad...
It also allows you to overlay local files, so you can change code while reusing server responses.
I've had the privilege of working in organizations that consider mistakes to be the cornerstone of resilient systems. Because of that, comments like this scare me, even when intentionally hyperbolic. More so, if the product works well and is being maintained easily, why would you micromanage like that? Sounds like a minor conversation only worth having if the technical decision is having a real impact.
Thomas J. Watson:
> Recently, I was asked if I was going to fire an employee who made a mistake that cost the company $600,000. No, I replied, I just spent $600,000 training him. Why would I want somebody to hire his experience?
You all are correct re firing someone over mistakes and seemingly trivial matters. I was mostly referring to software engineers who make impactful decisions without good reason and/or without properly assessing the trade-offs.
I think it’s fair to say that we all want performant software, but at the same time, if I have a software engineer on my team who can’t back their decisions with some form of data and/or understanding of the trade-offs, unless they’re at the junior level, they’re not the type of software engineer who I want on my team.
I said “performance reasons” precisely because, over and over and over again in my career, I’ve watched software engineers commit unreadable messes of code that were clearly premature optimizations and/or optimizations where the performance gains weren’t significant enough to justify the costs of the unreadable and hard-to-maintain code enabling them.
I once had a software engineer unexpectedly spend almost a week rewriting a critical part of a Java codebase using the JNI because he thought it’d “make it faster” — and it did — but then all types of new native code-related issues ensued that cost the company, including a major security vulnerability that was just impossible before. On top of that, it turned out that the performance gains that we noticed were mostly significant during the startup period of the JVM, so it really wasn’t worth it. And this was a very brilliant software engineer, but he was consistently making poor decisions like this. To be clear though, he wasn’t fired! I just use that story as a realistic example. (Part of me still thinks that he just wanted to learn/use the JNI and that project seemed like the perfect target. Lol.)
But yes, it’s more complex than simply firing individual contributors for sure and I regret wording my statement that way, but I hope you all can understand the real point that I’m making.
Edit: I’d like to point out that, in my anecdote above, in hindsight, if anything, I was probably the one who looked incompetent when the suits started asking the expected questions re the sudden set of new issues, because I did my best to shield that software engineer from them (or at least I’d like to think that I did). I know the feeling of messing up at that level and I knew that he was most likely already beating himself up, so I couldn’t just let him take the fall, or worse, throw him under the bus. These tend to be complex situations in real life!
As a dev who sometimes goes off chasing wind mills, that's 99% of the reason why I do it. I find something nice to tinker with, and when my brain goes "ooh, shiny" I stop giving a shit about anyone's bottom line.
To be fair, it usually turns out for the better for the project and its code base! But sometimes it doesn't, and I figure that's just the cost of doing business. Companies should be willing to take these kinds of informed risks in order to improve their employees' ability, and therefore the quality of their product. However, a lot of management only sees the short term gain, because long term gain isn't incentivized for them. They just wanna do well and get a promotion.
Well, guess what, it's the same for me. Except for me to do well, I have to be learning new things constantly. So tough poop, management, I'll be chasing my white whale every once in a while. Deal with it.
Perhaps they should be willing, but your description of this distraction does not including informing the Company and allowing them to determine whether it’s a risk they are willing to accept. You decided for them because you didn’t want to receive the answer “no” in return. This isn’t right.
I'm afraid the morality of this situation isn't so black-and-white.
In industry, there is always a tension between production and research: cranking out widgets vs. getting better at cranking out widgets.
A dev who spends 100% of their time cranking out widgets is stagnating. That's actually not what your employer wants, despite the fact that their agile process seems to imply that ticket cranking shall be the whole of your focus.
If you ask employers if they expect you to improve your skills over time, they would absolutely say "yes". But if you ask for permission to chase a specific white whale, you will hear "no". Everyone agrees they should be saving for the future, but "not this paycheck".
Taking the naive moral approach here and spending 100% of your time on tickets is not "what's right". If anything, that's you being taken advantage of by your employer -- sacrificing the advancement of your career in the name of short-term sprint velocity gains. On top of that, stagnation is not what your employer really wants anyway.
(edit: the above excludes companies which have explicit "20% time").
Was I born this way? No. I need this overhead, that's just part of being a dev (within reason).
If you require me to do lots of things, there's overhead. If you want a ticket drone for your Scrumfall projects, get a ticket drone.
That is something I've noticed. Brilliance doesn't go hand in hand with making prudent and wise decisions.
> I did my best to shield that software engineer from them
I've found rather painfully that you shouldn't shield guys like that when they go off on their own to make mistakes.
Other thing, you have a team of people that are familiar with how a codebase is put together and does things. And what sort of things go wrong. It's a bad idea to disrupt that 'just because' Goofus rewrites a module to use X fad. Great! Before there were five programmers who knew how that module worked and now there is one programmer who knows how that module works.
Additionally to contrast - if you're a co-worker and not a manager then you may need to examine your relationship (are you a mentor and thus secretly leading them or just a colleague). If a pure colleague makes a mistake you shouldn't stick your neck out too much - except to force your common manager to properly defend them.
Everyone who is fired should be fired by their manager and not anyone else in the org - that's how a team is strong and healthy.
And
Managers, in a healthy company, own the mistakes their subordinates make.
The other part of your job is keeping your manager informed about subordinates that are being problematic. Up and rewriting a critical piece of infrastructure 'because' is problematic.
It's a bit of a delicate balance. The golden rule is that Snitches get Stitches, but if someone is being unproductive with their time and your manager isn't aware of that fact then letting them know isn't a terrible idea. But it isn't your place to measure how your co-workers are accomplishing their tasks - assuming management isn't out to lunch then performance reviews should fall on their shoulders. Maybe your coworker cleared a rewrite with your manager and your manager was satisfied with the justification and decided that explaining the full reasoning would be a waste of time until the experimental phase was completed.
In theory good management should prevent you from feeling like you need to look over other people's shoulders, because that is their job. So if you are feeling that way you might want to talk to your manager about it, maybe they are bad at managing and are letting things slip through the cracks, maybe they find that allowing someone to experiment with a rewrite is worth the training time - it may be possible that you just need to talk it through with them and find more confidence in their management ability.
Reminds me that John's Carmack wife told Carmack that she wouldn't allow him to bankrupt the family with his space hobby company (Armadillo Aerospace) :)
Code inside string literals is less readable and more inclined to be wrong/buggy.
Firing easily for honest errors is moronic, fully agreed, especially if the person is learning from them. My code changes caused more than one sev0 before, but never was I personally blamed for them, as it was always some bigger underlying system issue that wouldn't have allowed me to make those mistakes, if the systems were more robust (and I was a little bit more wise and not pushed "seemingly safe" changes outside of business hours). I learned a lot from those mistakes.
Firing easily for a long history of non-improvement and not meshing well with the team (underperforming, causing a lack of cohesion within the team, etc.) is good for the team, but in principle it is similar to the "good king" kind of approach, so it all relies on the "king" having a straight head.
P.S. My last paragraph does not imply "culture fit" or any superficial stuff like that as a good reason for firing, I meant more fundamental sort of issues, like refusing to listen to people, never even attempting to improve (given you have some hiccups, just like most of us), etc.
additional counterpoint: part of your job as being a grown up responsible adult is your ability to manage and endure risk and loss, especially the risk of your job disappearing overnight. Outside of circumstances of extreme poverty, or extreme disability, in which our government has safety nets in place (let's save the debate of sufficiency for another time, the fact remains they are in place), losing your job should not "fuck up your life" moreso as be a temporary setback. This is especially true for this industry.
I’m not saying the UK or other European counties have the perfect healthcare systems either but at least we aren’t tied to a job we don’t like because losing our company’s health scheme is too scary to consider.
Also, traveling to the US for treatment is still a thing, because new, advanced treatments are developed and first implemented in the US, so all that money spent give you something in return.
Sometimes it takes almost a year to resolve.
BTW, even basic surgeries in the US can have a price tag of close to $100k. I've had to fight off more than one ridiculous bill like this in the last 5 years. If you're talking about medical tourism coming into the US, I can't imagine you're talking about anything but very well off people.
It sounds like you’re saying America is the only country in the world developing new and advanced treatments and the only country people travel to for such surgery. Clearly that’s not even remotely true (and even if it were, which it isn’t, it still doesn’t justify just how badly broken your healthcare system is for domestic users).
Considering US hospital bills can easily be tens of thousands, a couple of hours wait at even $1000/hr. billable lost opportunity is still cheaper than the US alternative.
That plus your emergency savings funds, should more than account to hold you over 6 months to find your next role. 5 years ago. I'll save my survivorship bias story for how I coped with this exact situation 5 years ago because I know everyone's situation is unique, but the lessons of growing up with 2 unemployed parents and living month to month not knowing if the bank was going to repossess our house have stayed with me I guess.
I see too many programmers being too clever and then leaving their clever code to become someone else's issue. My advice is be simple and make readable code. No one wants to maintain the clever code of another person.
The problem isnt that maintainble code isnt worth the effort, the problem is that firing people until someone matches your demands is not the most effective way to GET maintainable code.
Seriously though, there's clever code and then there's just nitpicking. Micro-optimizations with JSON.parse() look ugly and nullify some editor conveniences, but they're IMO very far from being a fireable offense.
One should always optimize for easy maintenance. Performance is always a secondary goal, because it doesn't matter how fast (you think) your code is if you can't understand it.
The question is WHY did they do that? I'd probably get them to learn about performance tuning and do some profiling, make something faster. When they find out that it's slow because of something they didn't predict, hopefully they'll decide for themselves that they can't predict what will be slow, so no point complicating the code. If they don't get that, maybe explain it to them.
Basically the person who put JSON.parse all over the code was learning.
If they come back and arrogantly say "I'm right, and I'll carry on doing it you won't stop me", then that could be an attitude problem that might lead to question if they should be working there.
There are more nuances like if the person is claiming to be a senior developer/architect then the trigger for firing them might be more likely to be pulled. But still it is worth thinking about it first.
Yep, and I'd fire you for doing that! There are better ways to manage instead of showing off your authority. Oh, and by the way, would some JSON.parse statements for performance be the worst thing in your codebase(s) you guess? I mean, I cannot believe that would be the worse in your codebase. Also, if it really helps to use some JSON.parse for creating big objects for performance reasons, who cares? Instead of firing 'someone' maybe you can add some annotation to it for readability (or if that is below your imaginary level, ask the developer if he/she can add that).
Sry, but I hate people that misuse their authority by imposing their subjective opinions.
Seeing something like JSON.parse throughout the code is definitely a code smell and could decrease the maintainability of the codebase, and that's a very tangible problem. Obviously you shouldn't fire someone over something like this if it's the first offense, but it definitely raises red flags and should make you monitor things a little more closely. If they show a pattern of dogmatism and poor judgement, you're probably better off finding someone else with better judgement. You're not going to find a perfect employee, but some employees are just better at making decisions for a larger project than others.
"Those responsible for sacking the people who have just been sacked have been sacked"
"The directors of the firm hired to continue the credits after the other people had been sacked, wish it to be known that they have just been sacked."
But now with static types - this would totally wreck static type checking. And you would need to spend additional cycles to validate that the data is actually correct.
Definitely a change request in the PR.
This has to be probably a really big validate perf advantage to warrant the loss of static checks.
(This reply assumes you're not asking for TypeScript to make a major philosophical shift and start generating runtime code to validate types. If you are, that's a discussion worth having but goes way deeper than `JSON.parse`.)
One thing I have seen from managers who don’t work regularly in the codebase — they tend to over-focus on things like whitespace and function names more than correct abstractions, separation of concerns, etc.
See Java’s whole “abc”+”ced” vs StringBuilder performance issues. When programmers have to alter readability for performance, it doesn’t necessarily mean they shouldn’t do it, but it means the precompiler is not advanced enough.
Readability is crucial in code. If you have to through and change the JSON that's being parse and it takes a nontrivial amount of time, that's a big setback. Sure, it's 1.7x faster (in v8) to parse JSON, but how long does it take to parse 10kb of an object literal in the first place? Given that these static, large objects are not common place in a codebase, is it worth the tradeoff?
The precomiler, such as Babel, could introduce a plugin for this sort of optimization. We only write ASM when it going to significantly change the performance characteristics, and typically when a particular code path is run many, many times throughout an application. If an object literal like this is getting parsed that frequently, there are better ways to optimize so that doesn't need to happen at all anyway.
I could see this being very useful in a variety of applications, such as server side rendering. However, its would be best to happen in an optimization phase as you're already bundling at that point.
It never was clear to me why they didn't do both of those in the same release. Backward compatibility wasn't the problem (they were already breaking that left and right).
When the compiler switched to generate StringBuilder (unsynchronized) concatenations for "abc" + "def" nobody benefited, because they had already changed to use StringBuffer (synchronized).
Now they had to go an undo all of their hard, manual, optimization work.
I feel like the same would/might play out here.
noun exaggerated statements or claims not meant to be taken literally.
I'd argue that if you have 10kb or larger object literals in your codebase, you are already missing the mark on readability and maintainability in some ways.
- exporting data from server to client for initialization
- localization data
- environment variables (feature maps, configuration etc)
- preloading datasets for graphs/tables
Protobuf isn't built into the browser, so it can't bypass the JS parse & execute time. Instead you'd be parsing protobuf's JS, executing it, parsing proto, and producing objects. It'd be worth doing, sure, but it'd almost certainly be the slowest option by far since it's doing way more stuff in JS than either of the other two options and the JS syntax parse is the slow part.
At the end of the day, who knows if the use case hits edge cases or stresses parts of the implementation that is not optimized for JSON decode or protobuf. Getting meaningful performance data ultimately needs to be experimental, and resists categorical answers about whether X is faster than Y.
1. https://www.npmjs.com/package/protobufjs#performance
This article goes into a bit more detail: https://auth0.com/blog/beating-json-performance-with-protobu...
We're exclusively talking about cold start performance here. Single, one-time object creation. Hence why JS syntax parse is the dominate factor and not execution performance. Those benchmarks are not that, they are hot performance. That's a completely different thing.
> Not to mention end to end load time (which is probably what people are usually trying to optimize for) can be lower by reducing how much data needs to travel over the wire or radio.
Wire transfer size would need to be looked at differently. The JS code & JSON string are both also going to be compressed unless you're not using a compressed Content-Type for some reason.
1. Having a static JSON string, and decoding that string.
and
2. having a static blob, and using protobufs to decode that blob.
these two things accomplish the same thing. I'm not sure why you seem to think one is a "cold start" and the other is "hot" - they're both "single, one-time object creation". The former is going to be parsing ints and floats as ascii, and reading in "true" and "false". Regardless of compression, the memory-inefficient JSON encoding is going to be used (whether it's over the wire, or just as an intermediate representation during parsing). I've used protobuf decoding for things like localizations and configurations before - the "cold start" use case you're talking about - and it does in many circumstances result in faster loading. My napkin paper reasoning is that this will be much more heavily weighted to booleans and integers that are much more efficiently encoded in protobufs than JSON, so maybe if you had a use case that almost entirely decoded strings your performance differences may not be the same.
you created a noun to describe "fat data" from a typo.
I interviewed a developer and asked him to explain how the system he was currently working on worked on the whiteboard. As he talked he drew two boxes. He drew a line between those boxes. Then as he talked he kept drawing over the line between the boxes. (Now, he was jr to mid-career so I didn't expect a magnum Opus but we value people who can explain themselves because at least if they're wrong we find out before the mess gets too big. But I digress.)
Your analysis reminded me of that interaction. What kind of information architecture do you have if you're building objects that big?
I mean, as others have said, if this is the main payload being transferred from client to server, it's probably going to arrive as JSON and you're going to turn it into Objects.
If it's not that data (they're talking about cold loads) how many other categories do you have that can approach 10k?
Configuration? We have libraries for that and they often read a JSON file.
Lookup tables for fixed relationships of data in the system? Maybe, but that complicates your testing situation.
How many of those categories get loaded more than once per session? Are these really such large startup bottlenecks that we tackle this instead of other problems? GP implied incompetence but I get more of a whiff of desperation here.
I don't know about that. Prioritising making your own job easier over the experience of all your end users feels like a much more fireable offense to me.
In this particular case I'm still a little wary of it because it feels like it's optimising for a current implementation with no idea what the future performance implications might be (or current implications in non V8 engines?) but this trend of prioritising developer experience over everything feels like a very bad one to me. It's the same reason given to justify making every web site a React app with no thought toward the extra JS payload you're sending when it's not needed.
This assumes the cost of dev time is equal to the cost of CPU time. In some cases the additional speed is going to return more value then the cost of the dev working. And other time the additional value of getting the product to market is going to win out.
Deep-copying JSON objects using stringify+parse is not just faster, but less problematic and less code than writing a recursive object copy routine.
> This knowledge can be applied to improve start-up performance for web apps that ship large JSON-like configuration object literals
Third paragraph...
> A good rule of thumb is to apply this technique for objects of 10 kB or larger — but as always with performance advice, measure the actual impact before making any changes.
I'd fire people who don't RTFM
Not only would you be missing out on readability, none of your linters will catch errors within that string any more and if you use something like prettier, well, god help you. You’re almost guaranteed to introduce more wasted time than you’ll save with this doing it manually.
I don't remember the specific numbers... it was an easy change in the server handler for the base.js file that injects a __BASE__ variable.
var clientConfig = JSON.Stringify(base.Env.Settings.ToClient(null)).Replace("\"", "\\\"");
// NOTE: JSON.parse is faster than direct JS object injection.
ClientBase = $"{clientTest}\nwindow.__BASE__ = JSON.parse(\"{clientConfig}\")";
...
return Content($"{ClientBase}\n__BASE__.acceptLanguage=\"{lang}\";", "application/javascript");
The top part is actually a static variable that gets reused for each request, the bottom is the response with the request language being set for localization in the browser app.On the other hand, knowing the performance characteristics, this is something that compilers could do as an optimization. Who knows if that's worth the effort, but this kind of research is part of determining that.
You could then use the same string in JSON.parse(...) in your JavaScript, json_decode(...) in your PHP, JSON::Parse's parse_json(...) in your Perl, json.loads(...) in Python, and so on.
If you do have constant data that needs to match across multiple programs, it will probably be better in many or even most applications to store the constant data in one place and have everything load it from there at run time, but for those cases where it really is best to hard code the data in each program, doing so as identical JSON strings might reduce mistakes.
Guys - I think he was being hyperbolic. Ya know, like everyone does on the Internet. If he had said "if I had to look at JSON.parse(...) lines constantly, I'd jump off a building!" I doubt you all would be calling 911 over an attempted suicide.
Seriously, chill.
I'd stick that JSON in a separate file, get typescript to compile it "just to check it's OK" then get the compiled code and include it as a string using something like https://webpack.js.org/loaders/raw-loader/, I guess (not used it before).
There might be a leaner way to do this (maybe the whole thing can be done as a webpack loader in one step), but something like this.
Which that’s the crux of the issue here, your opinion.
And as you say some people do write at scale.
> code readability and maintainability are just as important (if not more).
This is wrong, that’s all I was saying. Code right and it is readable anyway
const injectedValue = JSON.parse("$SERVER_JSON_VALUE.replace("\"","\\\"")");
// vs
const injectedValue = $SERVER_JSON_VALUE;
generally for a single value in the codebase is emphatically NOT a huge issue... and if it saves 80-120ms or so on the load, that's a significant impact. Not to mention the lower memory overhead while doing so.If you're concerned enough about performance, or message passing costs are enough of an overall performance bottleneck, that parsing your messages even 1.7x as fast is worth changing the way you code, you probably shouldn't be using JSON as your message format in the first place.
Any idea what the timeline for such changes could be? Personally I'd welcome the possibility of compiling complex web apps down to WASM, but I can't see the things you mention happening any time soon
That’s essentially what flatbuffers is. Slightly larger than protobuf but insanely fast to parse since it doesn’t need to scan the whole file. It’s both memory and CPU efficient. Netflix uses it in their app because TVs can be low powered devices.
That’s why Netflix feels so much lighter than amazon, hbo or Hulu. They all freeze my Vizio TV but Netflix is smooth.
Why is that an issue? Do websites need to be open source? How many people, including software developers, will actually view the source for a 3rd party website and/or try to debug it? Beyond screen-scraping and learning purposes I don't see a use case for it.
I'd be quite happy with my browser(s) downloading and executing binary blobs if it means better usage of my devices' resources and bandwidth.
“Bloat” is a problem on, say, news sites with horrible ads and it’d be great if they kept it lean. Obviously they don’t need webassembly and binary formats.
But... there are also incredibly powerful tools (google maps and docs, quake in the browser, streaming services, etc) that push the boundaries, which these kinds of tech will enhance, or make possible in the first place.
That said, I'm going to also submit that, if you're shoving big enough messages at a fast enough clip that you feel motivated to be this worried about deserialization speed in the browser, you've also got bigger fish to fry.
Either way you cut it, it's at least worth stopping to think about whether you're being penny wise and pound foolish.
Let's set aside binary formats for a moment. I once sped up populating a large-ish table of data by an order of magnitude - and achieved a pretty decent reduction in data volume, too - just by switching the format to CSV.
Before:
["my", "data", 1, 2, 3]
After:
my,data,1,2,3
I'm surprised it is 10x faster.Not sure if I should end this comment with a /s or not.
[1] https://raw.githubusercontent.com/joypixels/emoji-toolkit/ma...
> As long as the JSON string is only evaluated once the JSON.parse approach is much faster.
So doing this would only work on top-level declarations, because the javascript runtime will cache the parsed JSON structure for subsequent executions (eg. creating an object in a loop).
I’m having flashbacks to the Java serialize vulnerabilities from a couple years ago.
ECMAScript and JSON do not have the same set of escape characters:
``` Note: It’s crucially important to post-process user-controlled input to escape any special character sequences, depending on the context. In this particular case, we’re injecting into a <script> tag, so we must (also) escape </script, <script, and <!- -. ```
Though, if you're dealing with a typed object server-side and/or loading into a .js file request, it's less of an issue, if you aren't supporting html markup in the object to begin with. In my own use case, both are true.
The appropriate DOM APIs don't take HTML strings in the first place. You shouldn't be passing HTML strings to JS.
The attacker is escaping JSON.parse to escape HTML.
The appropriate DOM APIs don't take HTML strings in the first place. You shouldn't be passing HTML strings to JS.
I'm not sure I can find a use case of such a big object declaration. Usually what you do is to get it from somewhere ( file, db - with nodejs, xhr ) where it's been parsed with JSON.parse anyway.
Without that, you could probably use Typescript today to spit out JSON whenever the compiler saw that it was more efficient.
As OP said, "subset of JS Objects". This subset of JS objects wouldn't support function calls.
And for some weird reason, doing that was faster than just doing MOV AX, 0 (which is literally "Move 0 into AX", so "AX = 0" in more familiar syntax).
Edit: Oh man, my fellow HN'ers, as I did, all jumped on the occasion to show off :)
Later Intel actually special cased it in the instruction decoding path for the later CPU's (starting somewhere around the PII/PIII era, but I don't remember the exact timeframe) so that it also does not consume an execution unit and it /effectively/ executes in zero cycles.
On a similar note on many RISC architectures NOP is actually something like ADD r0, r0, r0 and that too is usually special cased in the hazard stall and result forwarding logic (althought usually the special cased part is “ignore hazards that involve r0”)
In this instance, if the register always reads as zero, and can never be changed, then ADD R0,R0,R0 is, in effect, a NOP, so it gets special cased, and doing so avoids having to allocate an additional opcode explicitly to the "NOP" instruction.
Anticipating the question of "why is Rx (0 or 31 or ??) hardwired to zero?", that one is because it is useful for:
1) obtaining a zero without having to perform a load from memory
2) creating additional addressing modes by reusing another existing addressing mode
For #2, if the RISC arch. implements, say, base plus index addressing where two registers are added together to obtain a final address, using R0 as one of the inputs creates a direct addressing mode from the base plus index mode.
So base plus index could be written as load R5, R6+R7. Substituting R0 (assuming it is the hardwired to zero register) for R6 (or R7) results in directly addressing from the value in the other register, converting an 'indexed' addressing mode into a 'direct' mode, without having to add a 'mode select bit' to the actual instruction. The result being that the chip only needed hardware for a single addressing mode, but the programmer has two addressing modes available for their use. If memory serves, the DEC Alpha made large use of tricks like this. The hardware only implemented a small handful of addressing modes (say 4-5) yet the full set of addressing modes exposed to the programmer was two or three times larger due to creative uses of "zero stuffing" into the actual hardware modes.
The important tuning piece for OOO processors is removing dependencies between calculations.
Math operations, on the other hand, are very simple to do because it's baked right into the CPU, only requiring one instruction and a few cycles
Such instruction didn't exist but I wouldn't call it ridiculous. It would actually be quite useful as setting a register to 3 is far more common than setting a register to 7911.
Since its instructions are always multiples of 16bit though, the immediate value is 8 bit, so slightly more useful, but the most common use of it was certainly setting a register to 0
(many architectures have done this: Intel has lots of short-form encodings for "op {al, ax, eax, rax} #imm", and ARM has Thumb, which basically chops the register count in half for all instructions to shorten their encoding)
https://stackoverflow.com/questions/33666617/what-is-the-bes...
This operation was almost always faster than moving a constant (like 0) into a register, because of all of the overhead of making the constant and reading and writing.
I know using spread
const clone = {...source};
Is faster than
object.assign({},source)
And seeing as in this case the source is already a js object it would probably be slow to string and the parse.
> As long as the JSON string is only evaluated once, the JSON.parse approach is much faster compared to the JavaScript object literal, especially for cold loads.
Edit: I think you would also need to identify and only optimize objects that are handled immutably. However, my understanding is that you can do that in a compiler/transpiler fairly easily.
Probably not, because the kind of object literals that can be converted to JSON.parse are the kind where you have different objects with the same shape, whereas reusing a memoized object would result in multiple references to the same object.
EDIT: wait nvm, that's what you addressed with your edit.
I'm thinking of compression libraries, or things like FlatBuffers.
This was only in IE 11 and edge. Chrome and Firefox took basically the same time for both.
I added them all to a new, detatched tbody. After my appending loops I removed the existing tbody then appending the new tbody to the table.
But if your goal is to compile a little closer to v8 then you’d have to set v8 as your compilation target, making that only really worthwhile on the server (since you’d be missing out on all other browser runtimes). I could see such a thing being pretty useful for something CloudFlare workers where startup time is vital, and your execution environment is guaranteed to be v8. Unless of course they’ve managed to always keep them hot.
where the double-brackets promise you're only going to do JSONish stuff in there
Because the JSON grammar is much simpler than
JavaScript’s grammar, JSON can be parsed more
efficiently than JavaScript.
Hmm.. shouldn't that hold for most programming languages then?Let's try it for PHP:
time php -r 'for ($i=0;$i<10000000; $i++) $data = [1,2,3];'
real 0m0,173s
user 0m0,161s
sys 0m0,012s
time php -r 'for ($i=0;$i<10000000; $i++) $data = json_decode("[1,2,3]");'
real 0m4,125s
user 0m4,120s
sys 0m0,005s
So for 10 million repetitions, a small PHP structure is about 20x faster then parsing JSON. But to test the point of the article, one should use the sama data structure it uses (https://raw.githubusercontent.com/WebKit/webkit/ffdd2799d323...) and parse it only once. time for f in `seq 1000` ; do php -r '$data=[1,2,3];'; done
real 0m11.169s
user 0m6.765s
sys 0m4.477s time for f in `seq 1000` ; do php -r '$data=json_decode("[1,2,3]");'; done
real 0m9.997s
user 0m6.093s
sys 0m3.974sThe correct comparison would be to try it on the 7MB json data the article is based on.
JS object literals allow such fun things as:
{
"foo": "bar",
foo1: function () { return "bar" },
foo2: () => "bar",
foo3 () { return "bar" },
get foo4 () { return "bar" },
["foo5"]: () => "bar"
}> Because the JSON grammar is much simpler than JavaScript’s grammar, JSON can be parsed more efficiently than JavaScript.
PHP does not re-parse code during execution.
$ time php -r 'for ($i=0;$i<10000000; $i++) $data = eval("[1,2,3];");'
real 0m10.568s
user 0m10.539s
sys 0m0.028sThe differences in data structures between the two languages may also play a significant role, what with PHP using complex z-val structs behind the scenes for almost all data types.
Is this notably a problem where the back-end is written in JavaScript?
Mobile browsers are the biggest problem, they (and desktop ie sometimes) can struggle with objects of even a few hundred kb.
(Though you can probably do some optimizations, such as treating "JSON.parse" as a keyword if you can be sure nothing tampered with it)
However, if that's the case, it sounds like a good candidate for an optimisation for V8: why not speculatively try to parse object literals as JSON and only fall back to JS if this causes an error?
Also, didn't their note about Chrome's bytecode cache kind of defeat their point? Yes, JSON would be faster on first load, but it should be slower on subsequent loads as the parsed object can be pulled from the bytecode cache while the JSON literal has to be parsed again on each load.
var obj = { "Name": "Joe`s sloppy place" };
will work well as plain object while
obj = JSON.parse('{ "Name": "Joe's sloppy place" }');
Will kill your site.. hard to control especially with several different unicode characters all being interpreted as plings by json parse..
var obj = { "Name": "Joe`s sloppy" };
will work well as plain object while
obj = JSON.parse('{ "Name": "Joe's sloppy" }');
Will kill your site.. hard to control especially with several different unicode characters all being interpreted as plings
The problem with object literals is the cost of code generation, in cpu time and memory usage, and then subsequent execution. The difference is so monumental that JSC will try to parse any JS first as a JSONP-style object literal, because the cost of attempting the object literal parse is so small.
For small literals that are hit multiple times, the literal will be faster in the long term - JSON.parse() results in opaque shape for the result which hinders lowering, etc, and the implementation is somewhat generalized to the case a large object graphs so many of the space improvements that happen for object literals don't happen.
People seem to love to dismiss small improvements, even if they're practically effortless. Remember, faster performance equals lower battery consumption. Bad slow javascript causes browsers to waste energy.
Small things add up.
What a time to be alive.
Someone asked if it was recommended everyone start refactoring their code to have this change and he replied it would depend on size of project/code etc..as the performance benefit might not be there for huge things, but in some smaller cases it could definitely be a plus.
[1] https://helpmepropose.live
EDIT: Does anyone know if there's something I could do differently to speed this up in Chrome?
Thanks again!
> JSON.parse('…') is much faster to parse, compile, and execute compared to an equivalent JavaScript literal — not just in V8 (1.7× as fast), but in all major JavaScript engines.
It's not just an idea, it's engineering with analysis. Smack on a pre-processor to wrap your cold start configurations (if they are large) and you'll get a performance boost, is the takeaway.
> 2x best-case performance is nothing
I'm not sure how you can say that with a straight face. Altering the bootup time of many systems by a factor is non-trivial.
It’s worth noting the caveat that there is a minimum size where this trick has a noticeable effect, though.
I understand the original comment’s fear of abuse. Nice to know it’s there for huge data structures though. Huge: we’re talking about a browser, not a database server.