JavaScript Is Way Too Slow – for What?

There's more to mobile web apps than JavaScript

I keep finding that programmers—even web programmers—frequently think “web application” means “JavaScript application.” Programmers are, of course, used to working with programming languages, and often see application environments from the perspective of the programming language in use.

These blinders derail Drew Crawford’s detailed rant on Why mobile web apps are slow. It turns out that “slow for what?” is a key part of the question, as Crawford reveals near the very end:

JavaScript is too slow for mobile app use in 2013 (e.g., for photo editing, etc.).

Do we need to run Photoshop on our mobile phones using JavaScript underneath? I agree that cramming everything into an interpreted language on a memory-, processing-, and bandwidth-constrained device is a stupid idea—but “photo editing” is an extreme case, to put it mildly. Perhaps critics will move on to video editing when we eventually get to the next round.

Despite that flaw, if the rant had been titled “Why mobile JavaScript apps are slow,” it would have done better. His lists of benchmarks, discussions of processor challenges, and recognition that the easy work in JavaScript optimization is already done, are all tremendously useful. There is little reason to expect JavaScript performance to improve in the future at the rate is has achieved for the last decade.

It may also be true that the browser vendors have optimized their performance as far as they can, at least in the relatively stable fields of HTML parsing and processing, and CSS selectors and formatting. Adding querySelector to the DOM was a massive one-time speed upgrade, letting JavaScript developers drop most of their tree walking in favor of a more declarative approach relying on native code in which vendors had already invested heavily.

So how can we optimize mobile web development?

The first answer is pretty simple: don’t try to use JavaScript for tasks (like photo or video editing) that push it past its limits. As far as JavaScript has come, it wasn’t built for that. Native apps are indeed good for more than building browsers.

The second answer is trickier: it means recognizing that web applications include much more than JavaScript. JavaScript began as a scripting language for gluing together objects written in other languages, and it still excels at that. Build your application from the HTML—the easiest stuff to process!—up. (If you want graphics, SVG might be a better path.) Then layer CSS on top of that. Rely on APIs built into the browser whenever you can, using JavaScript to connect with their much faster processing. HTML5 keeps making that a better and better option.

When I was programming our HTML 4 & 5: The Complete Reference, I marveled regularly at how tasks that seemed huge, like loading a new CSS stylesheet, moved rapidly compared to implementing smaller changes using JavaScript. More broadly, Estelle Weyl’s JavaScript: You Don’t Need a Framework For That (slides) resonates both because it shows how to use smaller chunks of JavaScript and because it explores how to use CSS creatively to avoid using JavaScript at all.

Building great applications using JavaScript, especially great mobile web applications, often means using JavaScript itself as sparingly as possible. That’s always been a feature of JavaScript, not a bug.

Related

Sign up for the O'Reilly Programming Newsletter to get weekly insight from industry insiders.
topic: Web Platform
  • Sean Hogan

    This reminded me of Eric S Raymond’s “Art of UNIX Programming” where he introduces the concept of the glue-layer. See http://www.catb.org/esr/writings/taoup/html/ch04s03.html#id2899777

    One quote:
    And one single bug-prone glue layer is not the worst fate that can
    befall a design. …
    Programmers who are bright but unseasoned are particularly apt to fall
    into this trap; they’ll get each fundamental set of classes
    (application logic, midlayer, and domain primitives) right and make
    them look like the textbook examples, only to flounder as the multiple
    layers of glue needed to integrate all that pretty code get thicker
    and thicker.

  • http://www.welovedc.com/ Don Whiteside

    I’m underwhelmed by your strawman. I read that article a few days ago and it’s a fantastic and detailed examination of various tradeoffs and progress in mobile/JS. He mentions the players he’s focused on here, iOS developers, right in the second paragraph, clearly setting up a comparison between native apps and web apps.

    Essentially you’re complaining that while writing a long, detailed, well cited article he failed to spoon-feed you the exact message you’d like – choose the right tool for the job. Which is a perfectly good bit of clarification for you to want to put on it, in your short article which has all of 3 links – one of which is self-promotion. But don’t slam his efforts because it’s not beating your exact drum.

    If the world only had room for one of these two articles I think it’s pretty clear which one the universe could more easily live without.

    • Simon St.Laurent

      Crawford’s piece is a great rant. Unfortunately, he forgot to cover a lot of the technology that’s included in his title. I agree that his piece is more important than this one – but sometimes even great pieces need a correction.

      Context matters, and the Web isn’t just JavaScript. That’s not just my drum.

      • http://www.welovedc.com/ Don Whiteside

        Except that the context is already in there for anyone not looking for an argument. You claim he buries that is, for you, the lede when you say “as Crawford reveals near the very end” but he does plenty of setup up front about what he’s interested in talking about.

        Graf 2: “but I can guarantee this is the most complete and comprehensive treatment of the idea that many iOS developers have–that mobile web apps are slow and will continue to be slow for the forseeable future.”

        Graf 4: “if you are looking for that 30-second buzz of “no really, web apps suck!” vs “No they don’t!” this is not the article for you.”

        Graf 5: “if you are trying to figure out exactly what brand of crazy all your native developer friends are on for continuing to write the evil native applications on the cusp of the open web revolution”

        Graf 7: “if what you mean by “web app” is “website with a button or two”, you can tell all the fancypants benchmarks like SunSpider to take a hike. But if you mean “light word processing, light photo editing, local storage, and animations between screens” then you don’t want to be doing that in a web app on ARM”

        Your position that there’s clarity to be had, that there’s more to an app than just JS is fine. But you don’t open with the confidence to simply build on that, you have to fire out with this strawman assertion that the article is something it’s not. You get to any sort of point, rather than taking swipes, when you’re just a few paragraphs from the end.

        So if you want to seem like you’re really extending and clarifying rather than arguing maybe you don’t want to wait till you’re 70% done before getting to actually contributing something. Crawford sets up his parameters and then goes on at length. You kibbitz that the article didn’t target your specific solution set and give us 3 sentences of actual contribution.

        I’d have rather heard more concrete “do X rather than Y” than half an article full of fluff tearing down something that actually contributes knowledge, even if it’s not the knowledge you’re specifically interested in. You could have introduced this article with a one line “Crawford emphasizes native development over javascript but never talks about other HTML5 solutions” and gone on to give us some real meat.

        • Simon St.Laurent

          Mr. Whiteside, I’m not really sure why you protest this much. Do I remind you of someone you dislike intensely?

          I thought I’d made clear that I think it’s a great article – just one that could have used a more focused title.

          Your citations of specific paragraphs do nothing to convince me that I’m wrong about Crawford’s conflating JavaScript and the Web. In fact, your pointer to paragraph 7 makes me wonder whether Crawford has spent any time with CSS Animations, which make shifting between screens a mostly trivial bit of native processing. If I wanted to nitpick his article, that would be a great starting place.

          All I’m doing – which doesn’t require a longer article – is pointing out that he forgot key context. It’s not the strange challenge you make it out to be.

          • http://www.welovedc.com/ Don Whiteside

            Oh, then I understand: I don’t think you do make it _at all_ clear you think it’s a great article. After all, you spend 50% of your text setting up an assertion about programmers making a certain assumption and then stating that you think he’s doing the same, plus this odd editorial quibble about a minor editing choice like a headline.

            I protest because when I read Crawford’s piece initially I was impressed with the level of detail and analysis he brought to it. He sets up the basis of native iOS apps vs webapps and provides some basic example of what he thinks those mean. Then he spends a lot of time on Javascript specifically and talks about what sorts of future constraints JS progress is going to mean.

            So I don’t think he did miss key context. He’s clear about who the audience is and clear that he’s speaking about Javascript instead of native code. You assert a “derail” but I don’t think anyone reading that article believes it’s anything other than what it is: an examination of the ways JS is speed limited and unlikely to change.

            So if you think there’s room to provide some guidance and pointers to a third way, super – I’d be delighted to read that rather than criticism that this other person’s detailed article about JS benchmarks isn’t what you wish it was. But I question that you (a) contribute some meat to the conversation with specifics and examples, the way Crawford does, rather than (b) simply being one of the no-evidence complainers he anticipates near the end of the article.

            In particular I question your article’s strawman about Crawford because of the blanket statement you make in your concluding paragraph. To claim that Crawford is unreasonably conflating a real-world deliberate sparse-use of JS seems to fly in the face of recent interest and momentum in frameworks like Ember or tools like Moustache which make a virtue of shifting things to the JS layer.

            Trying to claim I have some sort of personal-level grudge with you is just bizarre. I protest because I think you’re taking swipes at someone else’s hard work with poor proof and providing little value-add. I would LOVE the article you seemingly chose not to write, identifying this other group of high-functioning webapps that choose their battle correctly.

            So if you remind me of anyone, it’s of a generic person who can’t find a way to simply build and expand on someone else’s work without spending some time – apparently half of your column inches – tearing it down first. “Blinders,” “flaw,” “would have done better,” and an assertion that this is somehow misguided/disingenuous by mentioning video editing – those are judgment words and you picked them. Feel free to disagree with my criticism, but do it honestly rather than trying to fabricate some mental flaw in me.

          • Simon St.Laurent

            Crawford happens to be wearing the same blinders as a lot of other people. That leads to a basic flaw in an otherwise great article, a flaw that people wearing those same blinders won’t actually see.

            Yes, there are judgments there. It’s a blog post.

            It seems very clear that may saying that hasn’t and won’t please you. You’ve already written many more words than I did in the first place.

            “JavaScript and the Web aren’t the same thing” has never struck me as controversial. Apparently it’s a harder sell than I thought.

            Eventually I expect we’ll publish a book on the subject, and we’ll see whether or not it passes your review.

          • http://www.welovedc.com/ Don Whiteside

            If the book is filled with unique material and not 50% grumping about what other books lack then I expect I will be quite happy with it.

          • Brian

            @simonstlaurent:disqus, it seems you didn’t know that level 99 Trolls are immune to the effects of the special attack: “reasonable attempt to diffuse a flame war within blog post comments”

          • Stephen LeMaitre

            I think studying diplomacy in Vanguard: Saga of Heroes should be a must for any serious blogger who attempts to converse with trolls.

            Once you can successfully convince a rampaging hobgoblin fixated on re-enacting the Boston Tea party to put down the box and go for a nice stroll; then you may move forward to the complexities of debating trolls.

            First you walk, *then* you fly, grasshopper.

    • davemethvin

      There was definitely a lot of technical detail in Crawford’s article. It tore apart a myth that nobody I know subscribes to.

      There are plenty of places where currently the web platform can’t hold a candle to native apps. That’s why the W3C and others are working on things like Web Components, WebSockets, WebRTC, WebGL, etc. because web apps are so compelling that it makes sense to find the places where HTML+CSS+JS can be a performance bottleneck and replace it with a native interface to do the heavy lifting.

      Now I’m trying to come up with a way to tell you to tone it down without stooping to the same tone as you’ve taken with Simon. Can’t say I have an answer for that yet.

  • Xileer

    I’ve seen some instant photoshop-esque effects creating using pure JS.

    Heck – Have you seen the Unreal Demo yet… ? If running the entire Unreal Engine in JS at 60FPS is too “slow” for you, then I don’t know what you’ll ever consider as fast…

    • anon

      Yes, but did you try running that ON A MOBILE PHONE?

      • Xileer

        The photoshop-style effects? Yes (And they were instant – Assuming a decent browser (Dolphin Browser or so))
        The Unreal demo? Not personally, but I know people who have at decent FPS

  • Dirk Starke

    To have a mobile app feel native a lot of JavaScript is necessary. And obviously the results are good, but still do not really feel native. JS isn’t there (and according to Drew never will be there). What else is the reason for even big companies like Amazon, Facebook, Zalando, Booking.com, Google, you name it, investing in native apps? Could it be you don’t need Photoshop as a killer app?

    • rizqidjamaluddin

      The reason is because native apps have other strengths: access to more APIs (camera, contacts, text/graphics engines, etc), have better offline and local storage capabilities, can push better notifications, and more. Additionally, they’re plonked on user homescreens (as this is their default location), which helps with user loyalty/visibility.

      It’s not necessarily performance, although, obviously, sometimes it can be.

      • Dirk Starke

        Oh, yes, but most of the mobile webapps I know lack the smoothness when panning, flipping, pinching, spreading. Woudn’t there be more JavaScript necessary to circumvent this? Would those webapps still be performant then?

        Webapps are already slower because the program code needs to be tranferred to the client (more often), not just the program data. This will be recognized by the user as a drop in responsibility, which equals performance in the user’s eye.

        • rizqidjamaluddin

          More often than not, this is because of developers not using the same UI paradigms (or emulating in software what should be done in hardware) that the OS uses. A lot of mobile sliders don’t have inertial scrolling, touch integration, 1:1 movement (where you can wiggle your finger on the screen and watch the slider wiggle in sync) or that “bounce-back” effect that users are accustomed to, so they appear to be less polished. Some mobile web apps do provide these with great effect. They’re just not very easy to design (especially since the slightest incongruence with native apps will be jarring the the user), so they aren’t commonplace. Same goes for swipe detection (again, emulated, so nowhere as sophisticated as native code), panning, zooming, etc. The bottleneck is less JS, and more in the complexity each app would have to re-engineer for the simplest of swiping and scrolling.

          As for loading time, yes, totally. That’s the toll webapps will always have to deal with, at least until HTML’s recent local storage and offline caching features mature well enough for apps to have decent “cold” performance. For this, I completely agree. But this is part of the whole issue of web apps, not Javascript.

        • Simon St.Laurent

          There are a few different pieces here.

          First, multitouch came late to the web, though there’s certainly work being done – http://www.w3.org/TR/touch-events/ for example.

          Scrolling and swiping used to require weirdly infinite seeming JavaScript all by themselves. CSS is taking over more of that burden, allowing for better use of native processing, as browser vendors add support for pieces that make it easier. I won’t claim it’s perfect yet, but it’s moving. (See, for example, http://www.sitecrafting.com/blog/quick-code-ios-webkit-inertial/ .)

          There are a few ways to deal with the transferring code problem. One classic way is packaging – use PhoneGap/Cordova or similar, and get it all there at once. Another is minimization. Write as little as you can and send the smallest workable set you can. There are also a lot of general code loading and caching strategies that can ease that. Loading while the user is looking at something else (NOT a startup screen, something useful) can also help.

          If you design an app meant to be loaded over the Web so that it doesn’t really start until all the JavaScript has arrived, you’ve made a terrible mistake. Hence my emphasis on HTML and CSS as key parts.

  • http://www.itoctopus.com/ itoctopus

    I find the reason that JavaScript is slow is because of bad code. The so called JavaScript libraries out there are full of bad code – most of this bad code is the inconsistency across browsers when parsing JS.

    Microsoft, Google, and Firefox need to sit down and standardize JS and CSS.

    • Phil T

      Hi fellow programmers,

      Javascript is badly written because it’s now used by real programmers who are used to
      real programming languages that have classes and types that are checked by the
      compiler. So when they write code in Javascript it’s converted, either directly or just
      from their head into unwieldly Javascript.

      Why not let the javascript compiler do this for you instead of working at this very low
      level.There’s a free compiler called classyscript at http://classyscript.com.
      The language is a super set of javascript allowing classes and inheritance but
      compiling to standard javascript which will run in the browser.

      Thanks,
      Phil T

  • http://www.opwernby.com/ Dan Sutton

    Good article. I’ve always viewed JavaScript as one of those things you use when everything else won’t do it: this isn’t to say I haven’t written a hell of a lot of stuff in it, but I generally use it for writing things like complex user controls which don’t exist in standard HTML, for stuff like passing data around embedded iframes and other stuff which is completely UI-specific; data processing and complex algorithmic stuff is generally (and I say “generally” because it’s not a hard-and-fast rule) better left to a real language in the server’s backend. I tend to find that as long as you keep callbacks to the minimum that allows the thing to work properly, and try not to write anything amazingly processor intensive with it, then JavaScript is great: just don’t view it as the primary programming environment for your application.

  • Snark Skent

    ““photo editing” is an extreme case” – No, it is becoming a core component of the most popular and useful (useful to social media junkies at least) apps on mobile. It is a fallacy to describe this kind of functionality as an edge case and to suggest that developers will ‘go native’ to implement it. As a result your argument is completely invalid. If developers did use JavaScript simply to augment as you advocate there would be no discussion of its failings. Straw man indeed.

    • Simon St.Laurent

      I don’t think Instagram and friends invalidate my argument at all. Images are certainly central to the mobile experience, but image processing is not nearly as central. Again, Crawford didn’t title his post “Why JavaScript Image Processing is Slow.”

      If the web folks find themselves feeling left behind by the lack of such powers, we’ll likely see another JavaScript API supporting native image manipulation. Maybe the feature set of Pixtastic (http://www.pixastic.com) or JSFeat (http://inspirit.github.io/jsfeat/#imgproc ) but faster? CSS Animations and Transformations certainly work fast enough and can take advantage of hardware acceleration, and this isn’t that much crazier a level of mathematical complexity.

      I know the Augmented Reality folks would like to do more than JavaScript supports. They have some pretty amazing dreams. I don’t think their dreams, or Instagram, make this point “completely invalid”. Photo editing remains a more computationally intensive task than most of what people actually do with their devices.

      • Simon St.Laurent

        I woke up this morning thinking about SVG filters as an already implemented native image processing library ( http://www.w3.org/TR/SVG/filters.html ). The Android browser is the key missing link ( http://caniuse.com/svg-filters ), but specifying an API to it might spur that last mile of development. Not an instant solution, but reuse isn’t that hard.

  • Drew

    > The first answer is pretty simple: don’t try to use JavaScript for tasks (like photo or video editing) that push it past its limits.

    One of the things that has really made me sad coming out of this article is all the people coming out of the woodwork defending, as best as I can tell, the right of programmers to write boring software. Almost as if to say, “Now, class, CRUD programmers are programmers too.”

    If people are writing boring software, that’s a bug, not a feature. And it’s something that we should fix, not accept.

  • ChadF

    Several years ago I came up with an idea of Distributed Javascipt (lacking a better term), which would be like BOINC, only using client side JS for doing calculations. So just about anyone could “donate” CPU cycles by simply visiting a website. Even back then, when the typical JS engine was considered very inefficient, it certainly would have been more wasteful than other distributed alternatives.. but in exchange for some efficiency loss, you could gain far more contributors (not willing/able to install native clients). And now a days, you (well, I) hear about people creating full VM emulators in JS that perform about as well as some native systems (and sometimes faster).

    When I mentioned this concept to my coworkers, they (well, at least one) said I was insane (the ‘eccentric/pushing the technical boundaries too far’ kind, not ‘call the guys with the white jackets right now’ kind).. and rightfully so, I suppose. I never did get around to building a simple proof of concept implementation though. Of course with any great power comes that responsibility thing.. while websites could use client JS to donate processing, it could also be used to steal CPU time.

  • Damian Yerrick

    “As far as JavaScript has come, it wasn’t built for that. Native apps are indeed good for more than building browsers.”

    Web applications are good for shortcutting the entry barriers in developing for closed platforms. It’s not exactly cost-free to get an application approved on the iOS App Store, Windows Phone (7) Marketplace, and Windows Phone (8) Store, and it’s even harder on the major video game consoles. But all of them have at least some sort of web browser.