The Browser's Main Thread Is Expensive

(kciter.so)

126 points | by kciter 1 day ago

23 comments

  • jonathanlydall 14 minutes ago
    Superb article.

    There was very little new information for me as I have applied some of these techniques myself based on having developed an intuitive understanding on how a rendering "thread" works and blocks, but for a less experienced developer this article should be incredibly enlightening and provide a solid understanding of what's happening.

    I employed use of yielding on a hobby project [0] I made about 15 years ago, particularly when it had to do lots of draw operations on a canvas. I also experimented with using worker threads to render pieces of it on a background thread, but at the time there was no way to copy the data efficiently between them and the main thread, one had to send the data as a base64 encoded PNG and the overhead of encoding, decoding and then copying it onto the canvas made it perform far worse than just doing it all on the main thread.

    The website also does Gzip decoding of uploaded files in JavaScript and the library I found at the time did all the work synchronously so could lock up the UI thread easily for 10+ seconds. I tweaked it to be able to yield every 200ms or something, the process of which was very educational, particularly due to it convincing me to never omit the curly braces after an if statement, I spent a very long time trying to understand why it wasn't working until eventually I realized a statement I added wasn't in the if statement's block. It's not that I didn't understand how if statements worked, it's that in my mind the lack of curly braces was initially invisible to me.

    [0]: https://mordritch.com/mc_rss/

  • larodi 1 hour ago
    Top article, kudos! applied some of these techniques previously, and they do matter a lot. thing is, when you learn/teach JS there is usually limited time left to talk these topics, and they are essential more than it seems.

    the whole point of cooperative multitasking is to yield now and then (back to the runner), so that it can process the drawing. Besides, at 60fps there's so much that can be computed once every N frames, and the eye does not see it, the animation flows.

    It becomes even more interesting when webgpu is involved, but the CSS animator is indeed very fast.

    note: some recent work of mine (newskool digital flyer sites) -> bsf.hmsu.org // nouveauxhivers.dub4powder.xyz

  • piker 2 hours ago
    Great piece, OP. We work in WASM and are considering web workers to help with rendering documents off the main thread in that context. I was surprised to read that ArrayBuffer is moved by reference only! Might be an option. Thanks for putting this together.
  • xnorswap 2 hours ago
    Excellent article, I went into it thinking the headline is obvious, but the examples are well crafted and it isn't just the obvious stuff.
  • jkhdigital 1 hour ago
    This article concludes with the following statement:

    > So much of development is trade-offs, and you have to choose according to the situation, which ultimately comes down to the developer’s experience and judgment.

    It’s a great article, but I think it is a bit behind the ball in framing scheduling problems as a matter of “experience and judgment”. The problem of allocating work to a scarce resource is one of the oldest and most well-studied in all of computer science. It would make sense to go consult a textbook on the matter before trying to reinvent the wheel.

    • TonyStr 1 hour ago
      Do you have any suggestions for books on the topic?
  • monxer 27 minutes ago
    One obvious tool that this article doesn't mention is Chrome's performance monitor. Many techniques in the article only have to be applied once you can verify that they are running slow.
  • andai 1 hour ago
    Brilliant, I had no idea about this stuff. Thanks for writing it up.

    On the price ticket example, on my device (Samsung A15, mediocre phone from 2024) I get 11 fps with the slow example and 30 fps with the fast one. (15 if I scroll!)

    Is that a case of the back pressure you mentioned?

    All the other (fast) examples are 60 fps though :)

  • nairboon 2 hours ago
    In the first example: doesn't pushing the button while typing cause the textfield lose focus? What's the point of the typing in the example?
    • lintfordpickle 2 hours ago
      I think the point is, if you click the '2.0s' button, you cannot re-focus on the input field for those 2 seconds.
  • Tepix 2 hours ago
    Nice examples, a bit repetetive perhaps.

    One thing that I found quite interesting to see is how the behaviour of the "4.000 particles" demo changes between the 5ms rendering and the "everything now" rendering.

  • Ayesh 2 hours ago
    Such an excellently written articles with really nice interactive visualizations!
  • adzm 2 hours ago
    I wish await in JavaScript could conditionally yield. Instead I end up having to use arounds like if (shouldYield()) await do yield();
    • baxuz 2 hours ago
      There's an RFC or two to spawn threads so I'm looking forward to that. The current way of workers + messages is tedious as hell.
  • TIMEFOLD 11 minutes ago
    DELETE ARTICLE BACK PRESSURE! .

    FLIGHT §%=

  • prodigycorp 25 minutes ago
    I want to do a blanket response to people calling this AI slop: the post was written in korean and translated to english. Calling this slop is judgment slop.
    • duskdozer 9 minutes ago
      The basic Firefox "translate this page" on the original is more readable to me.
  • tobiu 1 hour ago
    Actor Model, dedicated or shared application worker. Full support for multi-window apps. Resolved since 2019. 26000 commits in, and counting. You are welcome!

    https://github.com/neomjs/neo/blob/dev/learn/benefits/body/O...

  • sylware 1 hour ago
    The javascript web is. Restore the interop with noscript/basic HTML and it will lean towards sanity, something lost a few years ago.
  • TIMEFOLD 29 minutes ago
    localStorage is a webworker
  • TIMEFOLD 31 minutes ago
    SANDBOX MISSING

    .setTimeout(0)

    CANNOT C

  • TIMEFOLD 32 minutes ago
    Sandbox missing

    .setTimeout(0)

  • ahartmetz 2 hours ago
    Yeah, but if your website with, you know, text and stuff, doesn't do any stupid and unnecessary crap, it doesn't matter where the nonexistent unnecessary yet expensive code doesn't run.
    • another-dave 2 hours ago
      and if you have no website at all, it takes zero seconds to load.

      But for people who are developing websites that are more than just text, this is an excellently written article and great advice.

      It's funny, for mobile app dev it feels like the community are a lot of focused on staying off the main thread, this is the first time I've come across one for webdev.

    • nicoburns 10 minutes ago
      You'd be surprised how expensive it is to render text, although unless your page is very large you won't see it being slow on modern systems.
    • adzm 2 hours ago
      Well yeah but if you do actually need things like images, animations, high frequency updates, etc, this is actually a pretty good overview of how to approach it. Also learned that react uses posting to a MessageChannel to yield!
      • account42 1 hour ago
        GP is right that just like with garbage where "reduce, reuse, recycle" is the mantra, the first question for optimizing something should be if you need to do the calculation at all.
        • adzm 1 hour ago
          This is true as well, yeah, but it came off as dismissive of everything too. Personally I prefer information dense interfaces with minimal chrome, but there really is a certain joy when you get to use a well designed and optimized fancy reactive, immersive interface
      • voidUpdate 1 hour ago
        Since when do images need more than just an <img> tag and a bit of styling?
    • Tepix 2 hours ago
      Sure, but there are sites like HN and there are sites like https://earth.nullschool.net/

      What's your point? Are you saying all animations and rendering are unnecessary?

      • ahartmetz 2 hours ago
        My point is that many websites are using way too much technology for what they need to do, with correspondingly long load times and choppy runtime behavior.
        • dspillett 1 hour ago
          Correct. But if the page is, at least in part, an art piece rather than an information dump, or needs to do interactive rendering for its purpose (an editor like the markdown example, live updating status displays, games and other interactive toys, etc), then the tech is necessary and this article is useful.
          • manphone 1 hour ago
            Which is something like less than one percent of websites, and this technology is deployed much, much more widely.
            • dspillett 1 hour ago
              Again, correct. But “don't do this if you don't really need to do this” is rather pointless to say, hence is being downvoted, because people already being that sensible don't need to hear it, and those who are not are unlikely to listen. The comment is just noise, as unnecessary as the unnecessary animation and other gumf that it is railing against.
    • kodoman 1 hour ago
      Amazing how you are being so down voted, most webpages do utter crap that no one would want the webpages to be doing other then advertisers. Really most things should be text and if we lived in a more cooperative world everything would be easy to parse and manipulate text with some video and images and perhaps various well defined interface types for different services that can be implemented in various ways as to the users liking.
  • mschuster91 1 hour ago
    > So what if off-screen posts were left as empty shells that only take up their height, and got filled with real content as they approach the screen?

    Yeah fuck everyone doing that, hello Reddit, Outlook for Web or Bluesky. It makes searching on such "feed" pages with the browser's search function an utter pain in the ass, made worse by the fact that the platforms' own search functions are outright braindead.

    • prodigycorp 26 minutes ago
      what's your solution to the performance hit that you get when you load up the dom with a zillion things? long, unvirtualized threads will bring every decent computer to its knees.

      the sites could implement their own search to make it all work if they wanted to. they just dont. but blaming virtualization is not tit.

  • shevy-java 1 hour ago
    So this is AI slop written? Why would anyone believe I'd want to read AI spam?

    Also, the issue I see is who controls browsers as much more profound. We need to find a solution here, as the browser is too important to allow private companies to keep mankind hostage.

    Edit: Wow, and the praise-accounts. Is that new on hackernews?

    • ricardobeat 1 hour ago
      What signs of slop are people seeing here? Or is it just a knee-jerk reaction to encountering lots of text?

      I’ve worked in the field for a long time and see a carefully written, correct, calm article. No obvious AÍ tells in wording or sentence construction. It is a bit long - might have been inspired by ciechanow.ski

      • Lebenita 33 minutes ago
        "and there’s a reason for that" "The code isn’t slow. It just happens to be the code that’s holding the main thread." "dealing with the main thread becomes the important part" "What to remember for now is that holding the main thread for a long time is the same thing as freezing the screen." "One thing not to misread here is"

        I realize the author may not write native English, but this is not translation slop, it's AI writing slop.

        • duskdozer 4 minutes ago
          Somewhere along the line "machine translation" became conflated with "machine translation + LLM editing"
  • Lebenita 1 hour ago
    AI;DR – too bad as the content seems to be worthwhile, but then why not take the trouble to write it up yourself. Have it proofread/edited/spruced up all you want afterward, but don't have it do all (or most of) the writing.