17 ms·
The Cost of JavaScript in 2019
- tyingq 7y ago"On mobile, it takes 3–4× longer for a median phone (Moto G4) to execute Reddit’s JavaScript compared to a high-end device (Pixel 3), and over 6× as long on a low-end device (the <$100 Alcatel 1X)" Notable that they avoid the iPhone comparison. It runs circles around even the top end Androids for JS performance.
- Irelando 7y agoIsn't that a little bit irrelevant? It's not an analysis of phones, it's an analysis of javascript. If my $70 android phone takes forever to execute something, I dont really care if my friend's iphone does it almost instantly.
- tyingq 7y agoIf you are trying to make the point that low end phones are slower, comparing to the actual high end makes the point stronger.
- addicted 7y agoThese are V8 devs. Why would they bother mentioning what happens on an iPhone which explicitly disallows V8? As a result, they don’t have the tools they use to measure these stats on the iPhone either.
- cromwellian 7y agoThey’re comparing like with like. iPhone cannot run v8, if you throw the iPhone into the mix then you are not measuring v8.
- simion314 7y agoMaybe you misunderstand what this article is about, s not about what is the best phone, is about how JS is run in real world where not everyone has super fast internet all the time and not everyone has a super fast phone or computer. So if you are a web developer you get some good advice from this article related to JS not what phone to buy.
- tyingq 7y agoThey are making the point that low end phones are much slower in executing JS than high end phones. Perhaps to remind developers that their experience, on their phone, isn't the experience everyone has. I imagine a lot of developers have recent iPhones. They are, depending on benchmark, up to 3x faster than a flagship Android. Which means the top to bottom chasm is much larger than the snippet suggests. Noting it would strengthen their point.
- BubRoss 7y agoThis article is about the v8 just in time engine, which does not run on an iPhone.
- simion314 7y agoOK, sorry I missundertoo then the iPhone point, my bad, I interpreted it as iPhone is super fast so nobody should forget to mention in any article the iPhone is the fastest phone and Intel i9s are the fastest CPUs. I agree that we the developers should not forget that a lot of people have less powerful hardware. I sometimes hit thus problem at work, say we offer feature X like uploading an image and you can crop that image and apply a filter, how should I add this feature but not have the code even load in the browser if you don't intend to use, is there a pure JS way to do it? AFAIK thee is no good way to load a script at runtime and get an even when the file is loaded and parsed.
- Stratoscope 7y ago> AFAIK [there] is no good way to load a script at runtime and get an [event] when the file is loaded and parsed. You can do this easily by creating a script element dynamically and then either: 1) Listen for the load event on that element, or 2) Have the dynamic script call a function that is already loaded. Here is an example of the first technique: let script = document.createElement( 'script' ); script.addEventListener( 'load', () => { alert( 'three.js is loaded: ' + THREE ); }); script.src = 'https://ajax.googleapis.com/ajax/libs/threejs/r84/three.min.js'; document.head.appendChild( script ); https://jsfiddle.net/geary/szmc1L0h/9/ https://jsfiddle.net/geary/szmc1L0h/9/
- ksec 7y ago1. v8 isn't available on iPhone, so they couldn't really show any results. 2. Unless you have the Samsung SoC variant of just released Galaxy S10, pretty much all Android JS performance, including flagship, will be slower than the current entry iPhone, which is the iPhone 7. And since the current Android flagship, along with middle range and lower end still has another 4 years of life in it, with roadmap that shows very slow improvement in the middle to low end Smartphones. May be we should just go back and ship HTML instead?
- pmarreck 7y agoNot sure if this is news to you but the Chrome browser on iOS (as well as ALL other browsers on iOS, by Apple stipulation via app-store rules) uses WebKit underneath
- deleted 7y ago[deleted]
- dmitriid 7y agoIf you look at why the bundles are so big, the frameworks are so large etc., you’ll realise it all comes down to fighting browser deficiencies: - no declarative APIs for DOM updates - no good APIs to do batch updates - no native DOM diffing (so decisions on what to re-render have to be done in userland) - no DOM lifecycle methods and hooks (you want to animate something before it’s removed from DOM, good luck) - no built-in message queueing - no built-in push and pull database/key-value store with sensible APIs (something akin to Datascript) - no built-in observables and/or streaming - no standard library to speak of - no complex multi-layered layout which matters for things like animations (when animating a div doesn’t screw up the whole layout for the entire app/page) etc. etc. etc. As a result every single page/app has to carry around the whole world just to be barely useable.
- pier25 7y agoI agree that the browser has many deficiencies for the modern front end developer, but OTOH there is no real need to make huge bundles. As an example look at Svelte. It compiles down to super efficient imperative code without sacrificing the dev experience. A hello world weights like 5kB gzipped I believe.
- fhennig 7y agoI just had a look at svelte, and from the perspective of someone who isn't really a web developer, I think this is a the proper way to do it. All of the other frameworks seems so convoluted and to me it looks like people are reinventing the wheel left and right.
- M4v3R 7y agoActually, the minimal Hello world example in Svelte is 2.7 kB even before gzip. It's really awesome and I already used it in one production app, the results were pretty amazing performance wise.
- snek 7y agoThese things are being slowly worked on: https://github.com/WICG/display-locking https://github.com/WICG/display-locking https://github.com/tc39/proposal-javascript-standard-library/ https://github.com/tc39/proposal-javascript-standard-library... (https://developers.google.com/web/updates/2019/03/kv-storage https://developers.google.com/web/updates/2019/03/kv-storage) https://github.com/tc39/proposal-observable https://github.com/tc39/proposal-observable ...etc
- snek 7y agoThis is an excellent analysis of JS performance and usage, although it seems to suggest optimizing your site for V8 a bit too much. Also, the "LONG TASKS MONOPOLIZE THE MAIN THREAD. BREAK 'EM UP!" section header felt a bit on the nose.
- badfrog 7y ago> it seems to suggest optimizing your site for V8 a bit too much. +1. After seeing some opinions that Chrome is becoming the new IE over the past few weeks, I've switched to Firefox to do my small part in trying to prevent another browser monopoly.
- supakeen 7y agoWhich parts of the article aren't applicable to Firefox? It seems like most of these idioms should give advantages to SpiderMonkey (if it's still called that) and V8.
- madeofpalk 7y ago> BREAK 'EM UP! also amusing seeing it come from Google.
- Zardoz84 7y ago"With HTTP/2 multiplexing, multiple request and response messages can be in flight at the same time, reducing the overhead of additional requests." Oh... we are using Servlet 3.0
- keymone 7y agoUgh.. does anybody else have this feeling that no matter how fast JavaScript gets, average web app performance will not change at all? Kind of like with risk compensation principle - the safer your gear, the more risks you take on, we’re in the same spot with web/electron apps. JavaScript vms got so much faster than 10 years ago and yet all the web sites are much worse. Memory and cpu hogs. This is not something improving the vm can fix. There just is no competition so that customers could send a feedback signal saying that performance is unacceptable.
- snek 7y agoAs they get faster, people use that as an excuse to stuff more code into their sites. It's a very sad pattern.
- Spivak 7y agoWhat do you mean there's no competition? This feels like such a weird statement when there's competition in just about every market segment on the web. If you mean there's no competition where the differentiating feature between competitors is performance then well sure, that's a lot rarer. For user-facing applications performance only really matters in human time, and is pretty far down on the list of how people choose software over things like features, price, ease of use, etc.. Until performance becomes a big problem because the app/site becomes unusable it's basically no problem. Hackers might not like it but we're such a weird market to sell to. Not necessarily that performance is a weird preference but that by in large hackers are perfectly fine with woefully inefficient feature-packed apps for their "primary" apps like their IDE but then want super lightweight skeleton-featured experiences for everything secondary.
- keymone 7y agoLargest cost of JavaScript is having to write JavaScript. It’s insane anybody would willingly do that nowadays. I think literally everybody writing JavaScript secretly wishes they were using some other language with JS transpiler. I refuse to believe anybody can honestly say they want to write JavaScript code unless it’s code that makes them write less javascript in future.
- deleted 7y ago[deleted]
- vturner 7y agoCome around where I work... People actually enjoy the migraine that is web app development.
- keymone 7y agoI’m sure that’s true.. for some definitions of “enjoy” that involve no pleasure or happiness :)
- NohatCoder 7y agoI have yet to find a better package, when you transpile, debugging always has that funky thing with two different source codes where you wrote one and the other is what is running. And it is not like you can do anything that you can't do in JavaScript, either you have a feature subset, or you ship with a library that the transpiler attached.
- blunte 7y agoYou miss the point. The issue isn't whether it's nicer to use a transpiled-to-JS language or JS itself. The issue is that JS as the root is an unfortunate situation, and there are so many other languages that would be superior. Just look at the history of JavaScript. It does not deserve the attention or human time that it currently gets (compared to other languages, assuming we could all decide simultaneously to replace JavaScript with another language).
- elbasti 7y agoAs a JS dilettante, I found this incredibly surprising. const data = { foo: 42, bar: 1337 }; // >>> can be represented in JSON-stringified form, and then JSON-parsed at runtime: const data = JSON.parse('{"foo":42,"bar":1337}'); // >>> 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.
- jasim 7y agoThis is great! Is the optimization applicable in Firefox?
- badfrog 7y agoI'd be interested to see some data on the real impact of "much faster". I can't imagine object parsing would be a large cost in the big picture.
- czechdeveloper 7y agoIt make sense if you think about it, but I would really not figure it out myself, that is true.
- mordechai9000 7y agoI read the comments before the article, and it took me a minute to figure out why: Of course, JSON is much simpler to parse than JS. For anything large enough to matter, I think you'd want to deliver it as an application/json blob, anyway. Or use protobuf.
- blondin 7y agoindeed! and i was going to say the same thing. it makes perfect sense if you are a programmer with a basic understanding of how languages work. but like someone else said, i would not have thought about it first thing when writing code.
- yyyk 7y agoPerhaps the reason many (like myself) did not immediately expect the speedup is that they started on or are still using another non-scripting programming languages. There, the language parsing penalty is paid during the compile step, and as far as a user is concerned the object approach is obviously faster than parsing from JSON. This does leave me wandering - is the result here applicable to other scripting languages too? The argument in the article would seem to apply in the general case, but perhaps other languages have some particularities that change the result.
- NohatCoder 7y agoTip no. 1: Don't put any code on the page that doesn't need to be there, then any minute differences in the exact implementation likely won't add up to much.
- yyyk 7y ago"Avoid large inline scripts" should be 'Avoid all inline scripts' in practice. Inline scripts prevent using CSP 'unsafe-inline' therefore increasing XSS risk. Performance is only a secondary problem here.
- bdibs 7y agoWhat’s wrong with the hash approach?
- yyyk 7y agoIt's not "wrong" in the sense of being intrinsically unsafe, but IMHO it's a bad habit which can tempt to insecurity in the end. When working with external files a programmer almost has to work with the framework, and once (s)he does that the framework - well, a modern framework - would take care of the security details and do it right. When working inline it's too easy to add a script tag manually, and from there it's a bit too easy for someone in the team to miss something (write a js without the hash/nonce and not notice the warning) or talk him/herself down to lowering security ("importing this 3rd party js is too hard, lets use just a nonce and forget about hashes", "this policy is too constraining, it's just a SMALL script, no risk here"). When working in a team, it's much better to have a hard and fast rule which forces everyone to work right. There's really no reason to use inline when using external files works really well now - and is apparently better for responsiveness too.
- eximius 7y agoWe use the nonce feature to allow inline scripts because (for legacy reasons) we don't have server side rendering enabled for our React app
- yyyk 7y agoIf you're stuck with legacy that's the way it is. Note however that there are interactions between using a nonce and caching which require caution (since nonce is supposed to be used only once but caching can work against that), so proper protection here has a cost in complexity and/or speed.
- blunte 7y agoThey left out measurements of "cognitive load".
- dehrmann 7y agoIt's interesting that they benchmark Facebook and Reddit, two sites I find significantly more laggy than, say, Google. Are there choices in how we build sites that are more important than how V8 can optimize things?
- nindalf 7y agoAre you comparing the Facebook news feed to the Google home page? Is that a fair comparison, considering the news feed does a lot more than loading static assets? Unless you were comparing the News Feed to say, logged in Gmail.
- OrgNet 7y agoGmail is certainly not faster then Reddit for me... too much javascript
- pepijndevos 7y agoI read the title as "the price we're paying for everything being written in JS these days"
- Old_Thrashbarg 7y agoSame, and I'd be more interesting in reading this alternative blogpost.
- root_axis 7y agohaha, programmers sure do love to virtue-signal with regard to JS. We get it, you're a sophisticated programmer that wouldn't be caught dead writing JS if you had a choice. It's a clever quip but not really contributing anything to the discussion of the topic at hand.
- dang 7y agoPlease don't cross into personal attack. We ban accounts that do that on HN. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- root_axis 7y agoOk. Just so I can understand a little better, in an ideal world, which part of my comment would I have omitted so that it wouldn't be considered a personal attack? I understand that the tone is sarcastic, but I am curious which part HN moderation regards as a personal attack. I didn't name call or use profanity, so it comes as something of a surprise to me.
- dang 7y agoYour comment was pejorative, and then you made it personal by saying "you". That's crossing into personal attack by HN standards. If one takes out the personal pronoun, the comment is still snarky, which breaks the site guideline "Don't be snarky." https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- badpun 7y agoHonestly, I thought this will be a post about the cost to civilization of something as sucky as JavaScript powering the Web.
- drewbt 7y agoConst data() = JSON...
- z3t4 7y agoAnother strategy is to make the files cacheable, and have some version naming scheme to invalidate caches. You can also lazy load features as most users will likely only visit the front page and then leave after 3 seconds. No need to have users wait for functionality they wont use.
- deleted 7y ago[deleted]
- hinkley 7y agoSeveral of the bundling tools have had a way to emit the file with a hash of the contents on the end of the filename, rather than using version numbers. One of the places this helps you is when you push out a one line javascript bug fix without invalidating your CSS caching across the entire site, because the CSS files are identical. It also helps you with people with the website open when the new code gets pushed. They either have all the old code or all the new code and no bizarre mishmash of the two.
- z3t4 7y agoWith making the files cache-able I mean not bundling them. The first load will be longer (unless you use lazy loading), but successive page loads will get the files from cache, and if there's an update, only that file will update. It's not usual to have updates shipped several times per day, and if there's many users there will also be many unnecessary reloads of the bundle. It's a bit of a optimization as to be 100% sure users always get the latest files the version naming scheme is needed, but most of the time it will work anyway, eg. if you have no caching layers /CDN etc in-front of the web server. So if you want to shave off milliseconds on first load, go with the bundle, but if you want to save user's bandwidth and make your site/app more lightweight - don't bundle!
- vimslayer 7y agoMost bundlers have ways of splitting the bundle into smaller pieces that can be cached (and cache-busted with the hash in filename) independently. I think that's what the parent commenter was talking about. So you don't have to choose between one huge bundle and hundreds of individual non-bundled files, with code splitting and lazy loading, you can do something in the middle and have like 3-30 "minibundles". Then, if you make a modification that only affects one of those bundles, only that bundle needs to be reloaded and others can still be served from cache.
- nullwasamistake 7y agoGreat article. I applaud the massive amount of effort that's resulted in JS being far faster than anyone ever expected. It's time to switch to WASM though. Half native speed with almost no parsing overhead. As integration and tooling improve I see no reason to stick with JS. It also rectifies a number of historical mistakes that are nearly impossible to fix. Mainly threading. WebWorkers etc are a huge hack. No atomic data structures, no shared memory, huge overhead. WASM will be many times faster than JS from threads alone. Add the natural speed advantage and you're looking at maybe a 20x performance difference.
- xenospn 7y agoThe last milestone I see on the WASM page is from 2017 - is it still a thing?
- nullwasamistake 7y agoIt's stable now and implemented in all major browsers.
- Siwka 7y agoLast time I checked you didn't get DOM manipulation, so you'd still need to use JS for that.
- nullwasamistake 7y agoYes. Rustaceans have stepped up and provided a ton of nice shim layers though. So practically, you don't have to actually write your own js to interface
- AlchemistCamp 7y agoWith their redesign and a few other choices, Reddit has gone from one of the most beautiful places on the web to the second most hostile UX that I put up with. I don't want to "GET NEW REDDIT" as I'm urged to in the top left of every page because I don't want a card-based layout. The whole reason I and so many others left Digg for Reddit to begin with was for a highly skimmable, information-dense site! Similarly, I don't want to install a mobile app. The page worked fine on mobile when I got my first iPod Touch a decade ago. Why do I have to see a huge USE APP button in the nav bar and then lose another 20% of the page at the bottom to a See Reddit In section at the bottom that's also urging me to install a native app? Infinite scroll actually slows down my browsing experience too, since it no longer loads as many entries at a time and I have to keep waiting for pagination.
- zinfour 7y agoRegarding card-based layout on the new reddit, you can change from card based layout in the top left corner on the new site.
- karmakaze 7y agoSweet! The compact view is even better than old.reddit
- OrgNet 7y agoI use https://ns.reddit.com https://ns.reddit.com along with Firefox's Redirector add-on to make sure that I always stay on that domain... not sure how much longer it will stay around though
- windsurfer 7y agohttps://old.reddit.com https://old.reddit.com is the "official" version of that, I believe. Here's a pretty popular redirector extension to go to that: https://addons.mozilla.org/en-US/firefox/addon/old-reddit-redirect/ https://addons.mozilla.org/en-US/firefox/addon/old-reddit-re...
- 7y ago
- lootsauce 7y agoCode splitting can be a nice optimization but it can also be a lot of effort for little gain as it is in our case. It is an optimization for the few times a user hits our app with a stale or empty cache. And we have no mobile users, this is an enterprise analytics app. We do not grow organically by people stumbling on our app and thinking "wow that was fast". We go through months of enterprise sales process to ink a deal, then onboard maybe 20 key users at the company. To put the effort into code splitting would be purely an exercise in keeping up with the new hotness. That's not to say we don't keep a close eye on the package size, just that it's not much of a great optimization for a regular user's experience in our case. Also serving all assets from the same domain saved us some time in domain resolution.
- nullwasamistake 7y agoThe last part, absolutely yes. CDN's are obsolete, although they'll jump through all sorts of hoops to convince you that's not the case. As long as your service uses HTTP/2 it's far more efficient from DNS and multiplexing/TCP/TLS handshake standpoint to serve from your own domain. And better for security most of the time since hardly anyone uses CSP and hash signatures for their third party scripts. The original sell of CDN was that everybody would have the same libraries cached. With the massive poliferation of JS you would have to have a 100 gig cache for that to be remotely true. A couple years back I moved a C# app to .NET core for the HTTP/2 support. I tried removing the ~4 external CDN dependencies just to see what happened. Load speed improved around 30% because no additional DNS lookups and TCP window stuff worked around by multiplexing. An aside, try not to use multiple subdomains. They trigger DNS lookups and don't work as well with CORS. It's easy to accidentally trigger cors and a bunch of meaningless round trips by using different subdomains
- billyhoffman 7y agoI think you are conflating general Content Delivery Networks with “shares JavaScript library repositories that happen to use a CDN”. While the “it’s a shared repo of common JS files so it’s already cached” idea never really worked (you are right about the added cost of DNS + tcp/TLS) general Content Distribution Networks absolutely provide performance benefits by delivering your static (and optionally dynamic) content from edge nodes that are much geographically closer to the visitor. Usually these CDNs front the entire site origin, so you dont have extra dns/overhead for subdomains like shared JS repos. (I work with many IR Top 100 retailers, and I’ve helped to build the dashboards comparing edge vs origin. It’s valuable even for sites where the majority of the visitors are in the US, and especially so if you have a substantial international audience)
- dep_b 7y agoI would also be interested in the cost of developer time lost by using the language itself and compensating for it’s almost entirely lacking standard libraries.
- lacampbell 7y agoI have usually found, installed and started using a good javascript library in less time than it would take me to make sense of MSDNs enterprise-soup documentation.
- manigandham 7y agoWhat does MSDN have to do with this? Are you talking about C# and .NET specifically? Have you seen the current documentation? https://docs.microsoft.com/en-us/ https://docs.microsoft.com/en-us/
- lacampbell 7y agoYes, I felt brave, so I went after everyones darling C#, and not an easy target like Java. I read C# documentation several times a week. I do not like it.
- gmiller123456 7y agoCan you provide some examples of documentation you do like? While I can't ever remember reading some documentation and saying, "Wow, that was fun!", so I can't say there's any documentation I like. But I do find that the MSDN documentation usually gets me working, and not reading documentation much faster than others for e.g. Python, Java, JavaScript, CSS, my pedometer.
- lacampbell 7y ago> Can you provide some examples of documentation you do like? MDN (Mozilla documentation for web stuff) is generally pretty good. Obnoxious colors aside, this javascript library is very easy to get started with: https://localforage.github.io/localForage/ https://localforage.github.io/localForage/
- superkuh 7y agoThis isn't quite true. It's only true if you're browing from a computer that is moderately fast (at short timescales before throttling at minimum) and using a browser that does not respect your software freedoms. There are literally hundreds of millions of us out there where executing javascript code on sites made entirely out of javascript can be significant. Weather it's because you use many, many tabs, or browse using an old smart phone. But of course that's not the real cost. That's the computation cost. The real cost of websites switching to an application model directly targeting the DOM is the loss of accessible webpages and the chance that every time you're going to get owned. Weather it's some information leak from speculative execution or something else. Running JS on every page these days is just as stupid as opening every attachment you get emailed to you.
- deleted 7y ago[deleted]