15 ms·
The DOM isn't slow
- bejar37 14y agoWhat is a good resource for understanding the DOM/query selectors and their performance (JS and CSS selectors)? All that I know about it is just through word of mouth and it would be great to look at a resource that covers these things. Also, is document.createElement('div') really much faster than $("<div></div>")? Just checked and a lot of well-respected JS libs use (including Backbone) use the jQuery version. EDIT: typo
- emehrkay 14y agoIf backbone didn't use a normalization library like jQuery, they'd have to write their own and I don't think that is the aim of the project.
- masklinn 14y agoNote that backbone is also compatible zith Zepto though.
- emehrkay 14y agoAccording to Backbone, Zepto is jQuery as it has the same interface.
- lucaspiller 14y agoThe normalisation is purely to support older browsers though. Backbone doesn't really use that much of jQuery, have a search for 'Backbone.$' through the annotated source [1]. There are only 10 uses of it in the whole file, and not for anything too crazy. In modern browsers you could probably do away with jQuery and still avoid "if safari then...". [1] http://backbonejs.org/docs/backbone.html http://backbonejs.org/docs/backbone.html
- recuter 14y agoThere are good talks by the Chrome dev team from various GoogleIO's. CSS selectors used to have a lot of voodoo about them but no longer matter that much in terms of performance. Try the blog of one Paul Irish and spread out from there.
- bzbarsky 14y ago> but no longer matter that much in terms of performance That's not quite true. They matter enough that WebKit is implementing them incorrectly because they can't figure out how to make a correct implementation performant enough...
- wmil 14y agoI haven't seen any profiling of jQuery, but last I heard createElement('div') and appendChild was slower than innerHTML ="<div></div>".
- MatthewPhillips 14y agoThat used to be true, but nowadays it depends on the browser and the difference is a rounding error.
- dclowd9901 14y agoThen why wouldn't jquery just proxy it? It's not like the creators are shitty at JavaScript.
- dsego 14y agoThat's not true any more: http://jsperf.com/fragment-vs-appendchild-vs-innerhtml/8 http://jsperf.com/fragment-vs-appendchild-vs-innerhtml/8
- no_more_death 14y agoStep 1: Learn to use the CSS profiler in Chrome. Also, here are some articles I found in my links list: CSS Stress Tester Bookmarklet (Copy into a bookmarklet. Then it will tell you the rules that are causing the most lag.) javascript:(function(d){var s=d.createElement('script');s.src='http://andy.edinborough.org/Demos/css-stress/stressTest.js?_=+Math.random();var http://andy.edinborough.org/Demos/css-stress/stressTest.js?_... es=d.getElementsByTagName('script')[0];es.parentNode.insertBefore(s,es);var doit=function(){if(window.stressTest){stressTest.bookmarklet();}else{setTimeout(doit,100);}};doit();})(document); Old but still relevant I think: http://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/ http://www.stevesouders.com/blog/2009/06/18/simplifying-css-... Text makes CSS slow (don't render too much): https://news.ycombinator.com/item?id=2232212 https://news.ycombinator.com/item?id=2232212 In general, following good guidelines might help: https://github.com/csswizardry/CSS-Guidelines https://github.com/csswizardry/CSS-Guidelines
- emehrkay 14y agoI went to a meet up a few weeks ago on Sencha Touch and how they did the Fastbook (http://www.sencha.com/blog/the-making-of-fastbook-an-html5-love-story/ http://www.sencha.com/blog/the-making-of-fastbook-an-html5-l...) project to prove that HTML5 is, indeed, ready to provide host an application as complex as Facebook a few weeks ago and it opened my eyes in a few ways. This article is correct, and provides an example, in saying that the DOM can easily create thousands of elements in milliseconds. However, the problem is that events and interactions with it all happen on a single process. Things load and block the thread, an event happens and blocks the thread, etc. The Sencha guys did something really smart. They used an object pool with one object: requestAnimationFrame, as the core of their mobile platform and sent EVERYTHING to it. That way events, loading, or whatever, didn't block, but happened in a FIFO manor. They also kept the number of dom elements static and just reused them when needed, so an object pool of dom nodes -- no creating or destroying nodes. The things that make working with the dom slow isn't only creating nodes, but applying styles, listeners, and destroying them -- basically creating an application. I do agree with the overall premise that a lot of developers do not know the best methods/practices/patterns to utilize when creating complex applications. I learn new things daily and I hope that our community continues to teach itself and provide tools to make getting things done easier.
- Xion 14y agoHonestly, that doesn't sound like a best practice and more like a convoluted performance hack. It's one thing to use a pre-allocated memory pool for speeding up the creation of objects in native language like C++. Having to the equivalent while working several software layers above that is an example of extremely leaky abstraction. DOM and Javascript engines still need few more man-centuries of iteration to bring their performance closer to e.g. JVM which doesn't really require hacks like that anymore.
- ZoFreX 14y ago> e.g. JVM which doesn't really require hacks like that anymore. Is this the case? I used to be pretty in-touch with Java, but haven't been keeping up from the release of 7 onwards. I've picked it up again for game development, and 100% of the performance advice I've found is to use object pooling... but nearly all of that advice is years old, and I have no idea if it still holds true for JRE7 or even JRE6. It did strike me as something the JVM should be doing for me, so if that has been fixed, that news will be greatly welcomed by the Java game dev community.
- recuter 14y agoPrediction: Since jQuery2 is dropping support for IE < 9, it will never be as popular as its predecessor. We all owe John Resig a debt of gratitude for getting querySelectorAll into modern browsers. The next missing piece is the ShadowDOM/Templates stuff coming down the pipeline, but sadly that will probably take just as long for mass adoption.
- bengillies 14y agoIt would be more accurate to say something along the lines of: "it's often possible to get the DOM to perform a lot faster than it currently is for you", or even: "speed probably isn't the biggest problem you'll face with the DOM; inconsistency and weird browser quirks are". That said, the following things irked me: > Abstraction is more likely to increase speed, because someone smarter than you has written the bit that needs to be fast. That's a very sweeping statement that doesn't really describe the situation. It obviously depends on what you're doing, who wrote the abstraction and how much is being abstracted. > First: ignore pretty much anything Facebook has to say about DOM performance. They really have no idea what they are talking about. Sencha was able to make a version of the Facebook mobile app with their framework, and it was FASTER than the official, native app, and Sencha isn’t even particularly fast. If you create an app that has half the feature set of another app it will likely be easier to make it go fast. > Second: Stop using DOM libraries out of habit! If your target browser is IE8 or above, jQuery hardly provides any features that aren’t shipped on the host object anyway. document.querySelectorAll will pretty much do everything you need. jQuery is a tool, not a framework. Use it as such. jQuery provides a clean sensible API. Something that is currently still lacking from the DOM (despite all the improvements). document.querySelectorAll will definitely not do "pretty much everything" you need out of the box.
- michaelwww 14y agoI assumed he was talking about document.querySelectorAll in the context of selecting elements, not for additional functionality such as jQuery's fadeIn()
- bengillies 14y agoIt's the extra functionality that makes it useful though. document.querySelectorAll doesn't even support event listeners or forEach loops. I wouldn't call that extra functionality, I'd call that a basic requirement. It lets you select elements using CSS selectors. That's good and all but if you want to actually do anything with that you're better off using some sort of library that abstracts the awkwardness away (i.e. jQuery).
- mathias 14y agoI call linkbait/trollbait. > People often throw around the statement “The DOM is slow”. This is a completely false statement. Utterly stupid. Look: http://jsfiddle.net/YNxEK/ http://jsfiddle.net/YNxEK/. Ten THOUSAND divs in about 200 milliseconds. How is that even an argument? Just because you can insert a fragment containing 10k <div>s in 200 milliseconds doesn’t mean that the DOM is not slow compared to other operations in JavaScript. DOM operations are still the slowest operations you can perform using JavaScript in a web browser.
- niggler 14y ago"DOM operations are still the slowest operations you can perform using JavaScript in a web browser." You aren't refuting the author's point. "The DOM is slow" is based on an absolute timing. No one is making a relative comparison. In general its possible to argue that operation X is fast, even if X is the slowest of a set of operations, if you take an absolute perspective.
- mathias 14y agoThe reason people say “the DOM is slow” is because it’s slower than anything else in JavaScript, not because of an absolute measurement. If you’re calling JavaScript features slow or fast based on absolute measurements, you’re doing it wrong. Read up on JavaScript benchmarking. Create and run some jsPerf tests on various devices and browsers, and compare the results. You’ll quickly find that absolute numbers are meaningless in this case.
- bconway 14y agoHTTP Error 503. The service is unavailable. Maybe not, but...
- Mahn 14y agoFYI, browser profilers can't evaluate the efficiency of your jQuery selectors, which can be a bottleneck aswell depending on what you do. I personally use this: https://github.com/osteele/jquery-profile https://github.com/osteele/jquery-profile
- george12 14y agoI have had similar experience. Skipping jquery and calling native DOM methods directly can be surprisingly fast. Still I am curious in what the benchmarks actually say. The native DOM methods appear to return before rendering is done (at least in webkit). So when we get a 200ms benchmark for 10,000 divs I suspect there it is taking a longer than that to fully render.
- jfim 14y agoYeah, they do return before rendering is done. For example, this fiddle[1] inserts 100k svg circles; it takes 1000 milliseconds on my machine, but scrolling around takes several seconds. [1] http://jsfiddle.net/vHvZD/ http://jsfiddle.net/vHvZD/
- creativename 14y agoI find myself constantly trying to fight the urge to be lazy with JQuery, since I tend to forget the performance hit it entails. For some concrete numbers, I updated a JSPerf that I found to include a raw JS implemention. http://jsperf.com/creating-dom-elements/8 http://jsperf.com/creating-dom-elements/8 I was caught off-guard by the results - it appears that (even after multiple runs) the raw JS implementation is ~100 times (times, not %) faster. Definitely surprised at the drastic difference, although someone please correct me if I missed something in these simple test cases. This was with Chrome on Windows, by the way.
- RyanMcGreal 14y agoI got different results on Windows XP (don't ask). Using both Firefox 19 and Chrome 25, Direct append came in the fastest with modestly slower performance (around 5-10%) from the other methods.
- creativename 14y agoThat sounds way more realistic - I'm not sure what's going on when I'm testing, but I may try later to repeat.
- krrrh 14y agoVersion 10 of your test is really surprising. The raw JS append function just came out 250 times faster than the jquery direct append example, and 750 times faster than jquery append variable. This is on chrome for iOS.
- creativename 14y agoWow, yeah. Document fragments seem to be even faster than my original createElement. I'm really going to have to re-evaluate how I'm creating new DOM elements.
- korynunn 14y agoThis is the kind of thing I was hoping to inspire. Sure, use jQuery, but use it wisely. That said, literally never make DOM in it, for so many reasons...
- iwillreply 14y agoIt's strange you blame jQuery outright for slowness of the DOM, and reference the jsFiddle as your reference point of speed. Writing this utilising jQuery for DOM manipulation ( http://jsfiddle.net/YNxEK/7/ http://jsfiddle.net/YNxEK/7/ ) is getting me consistently faster results than the original fiddle ( http://jsfiddle.net/YNxEK/ http://jsfiddle.net/YNxEK/ ) on Firefox and Chrome.
- Guillaume86 14y agoYou just use innerHTML with a big string, it's not the equivalent of the original fiddle and it's not a fair comparison.
- latviancoder 14y agoHere is a comparison, that looks more fair to me: http://jsfiddle.net/d5geB/ http://jsfiddle.net/d5geB/
- masklinn 14y agoWhy not? The original fiddle uses a documentFragment and does a bulk-insert of that in the document itself.
- emehrkay 14y agoDude, you aren't creating dom nodes. Here is the equivalent: http://jsfiddle.net/EmEhRKay/YNxEK/10/ http://jsfiddle.net/EmEhRKay/YNxEK/10/
- iwillreply 14y agoWhy would you append on every loop. Rather than build the string and then append the whole lot on one block? If you compare the DOM of the original fiddle and the DOM of following the fiddle I posted. You will see they are the same. I'm not saying what I referenced is the 'best' way of doing things. But that the debate in the original article (based on the provided examples) is pretty null.
- masklinn 14y ago> Second: Stop using DOM libraries out of habit! If your target browser is IE8 or above, jQuery hardly provides any features that aren’t shipped on the host object anyway. Nope, sorry, 9 times out of 10 the provision is theoretical and the interface is garbage. querySelector is pretty much the only one which does not suck — hence it being used as an example every single time. * Querying or altering elements? Verbose shit. * Binding events? Verbose shit. * Delegating events? You've got 2 different specs, the most recent one is unimplemented and the older one is prefix-implemented everywhere (and useless as far as I know). * Inserting elements in a DOM tree? Oh boy you're going to have a fun time manually traversing crap until you can reliably use insertBefore. * Creating a node with text in it? You're in for 3 different statements, and that's if you're not trying to add attributes as well * Manipulating classes? Hello broken regex search&replace. Oh you're targeting IE9 anyway? Well fuck you still, because Element#classList is IE10+. * Playing with data-* elements? I hope you like getAttribute, because Element#dataset is MIA in MSIE. * And bulk operations? What, you think querySelectorAll or getElementsByClass is going to return an array? Dream on, you may get something array-like in DOM4 if you're lucky. That means IE15, maybe. Every single time I tried to get by with raw DOM, I fell back on zepto or jquery, life's too short for shit APIs and the DOM is exactly that. I don't code in raw DOM for the same reason I've stopped coding in assembly: I value my life more. Now there are issues with jQuery, but these issues are generally that jQuery makes it easy to do the wrong thing (it's important to note that it also makes it easy to do the right thing, and improves that all the time, the "ease of doing the wrong thing" is just a side-effect of making things easier in general, the library does not specifically drive the user to the wrong thing) (except for animation maybe) e.g. keep doing noop work on empty selections, repeatedly select the same elements over and over again instead of caching the selection or not realizing you're doing a batch operation of adding a class or event on hundreds of DOM nodes in a single line. The DOM itself does not fix this, it just makes these things so incredibly and obviously painful you look for other ways to do it to try and slightly alleviate the pain. You get the same result out of thinking, and not blindly using jQuery.each and the like. edits: formatting, classes manipulations, data-* attributes, matches/matchesSelector.
- MatthewPhillips 14y agoMaybe I'm neurotic but if I know I can speed up my application 100x by typing .addEventListener('click', fn) instead of .click(fn) I'm going to do that every time and not lose any sleep over it.
- Kiro 14y ago"Sencha was able to make a version of the Facebook mobile app with their framework, and it was FASTER than the official, native app, and Sencha isn’t even particularly fast." It was really laggy on Android, so no.
- MatthewPhillips 14y agoNo, the DOM is slow. I've worked on mobile projects that didn't use a single 3rd party library, no jQuery no underscore, the most I've used is polyfills for stuff like Function.prototype.bind etc. It doesn't matter. When you have a non-trivial thing to render in a list, not just a div with text content, and you start to scroll the browser stutters. Even if the list isn't particularly long (< 50 items). CSS animations are also rather slow in mobile browsers although this is getting better with every release. I actually find it a little bothersome that so much browser development these days is focused on JavaScript performance and JavaScript alternatives whether it is Dart or asm.js or whatever... when the DOM is the primary reason lag exists.
- dsego 14y agoYeah, the problem is if anything changes or even if you ask for the width of an element, it has to for some reason reflow everything or at least a big portion of it. So you have to keep interactions with element positions and dimensions to a minimum.
- readme 14y agoThe reason native is better for mobile apps is not that the browser's rendering engine isn't fast. It's that the browser is yet another turtle on top of an already bloated stack. He argues that the developers working on these browsers are optimizing them, and that we are not intelligent enough to trump their obviously superior coding skills. Well, I'm going to disagree outright on that point. Many of us are very talented. Add Webkit on top of the Dalvik VM and android SDK, and fragmented device ecosystem, and we're talking major disparities between the way your HTML5 app is going to run on different android devices. I have seen HTML5 apps that work great on phone a and b, but not on c, because well, c has a different webkit version! It's bad enough to have to write code for different browsers. It's really bad to have to write code for different browsers that will run on hundreds of different android devices. Back to the point you made about optimization: don't you think the developers of the native SDKs are making optimizations, too? And the lower level means we're way closer to the metal, lower on the stack, and ergo: less complex. I'd use HTML5 for a trivial app, like, a business's mobile website. But for anything serious, GO NATIVE! Note, my answer is for mobile browsers, specifically android. Even iOS should be marginally better on this, but really I've only seen HTML5 kicking ass on desktop browsers. I've yet to be impressed by it in mobile.
- Kiro 14y agoSo what would be an appropriate response to "What are your thoughts on jQuery?"?
- korynunn 14y ago"Used in moderation, jQuery is an exceptionally useful tool for assisting in DOM manipulation and compatibility, and simplifying APIs such as for XHR requests"
- dewitt 14y agoThe point the author is trying to make is perhaps a reasonable one, but what an inappropriate communication style. I don't know if the author realizes the tone is so off-putting, but I've found that supportive feedback and constructive criticism goes a lot further in professional environments than name calling and insults. Put another way, if someone on my team at work communicated like that I'd have a conversation with them about more effective approaches less likely to alienate or offend colleagues. There appears to be an uptick of hyper-agressive technical posts over the past several years. I'm not sure where it started, but I'm hoping it burns itself out soon. (If you're the author, I apologize for calling you out on this. Nothing personal at all, I just wanted to make the general point about tone.)
- bjhoops1 14y ago"Supportive feedback and constructive criticism" don't general page views though. :/
- tmh88j 14y agoAre you insinuating the only way to learn and improve is by being berated?
- bengillies 14y agoThis link seems relevant here http://meta.wikimedia.org/wiki/Cunninghams_Law http://meta.wikimedia.org/wiki/Cunninghams_Law
- iamwil 14y agohttp://www.paulgraham.com/disagree.html http://www.paulgraham.com/disagree.html Look under DH2. I didn't find his tone offensive at all, esp as a piece of writing. It's likely that he hears "DOM is slow" all the time, and is venting. And he's a far cry from Zed Shaw's kind of writing.
- otikik 14y agoConsider that the OP itself is already disagreeing with something (the assertion "DOM is slow"). If we apply the rules of your link to the OP, it doesn't even get pass DH1 (the title is already a name call, and later on it uses others).
- mistercow 14y ago>If all you are doing is making HTML elements, DO NOT USE JQUERY. That's pure premature optimization. I don't understand how people can still be making blanket statements about performance costs like this. Using jQuery to create HTML elements is fine. It's convenient and succinct, and it keeps your code consistent. Otherwise, you'll have two ways of creating HTML elements: one for when you are just creating an element, and another for when you need to use jQuery on it afterward. But if you do hit a point where creating HTML elements with jQuery is slow, you optimize that point and leave a comment explaining why you're doing it that way. People get these ideas in their heads that somehow they're going to be able to code everything super fast from the very start, and it's nonsense. All you're going to do is make it harder to maintain your project.
- MatthewPhillips 14y agoThe types of optimizations you are suggesting are extremely hard to track down. If you have a laggy list you only know that you have a laggy list.. changing a single $('<div></div>') to document.createElement('div') probably isn't the thing that will speed up your application. It's probably not a single function or even a set of functions that is causing the problem. It's probably that in order to gain the 'sticky' affect you want that jquery plugin you're using is listening to a window.onscroll or something, and unless you want to dig into the code of every library you're using you probably won't know why. When you're working in the mobile web and performance is important you want to know what every line of code is doing. Your application is probably going to be a little laggy anyways, but at least you'll know why that is and know where to target to try and fix it.
- mistercow 14y ago>The types of optimizations you are suggesting are extremely hard to track down Except that it's not, because you can use profiling in modern browsers to figure out where the time is being spent. >It's probably that in order to gain the 'sticky' affect you want that jquery plugin you're using is listening to a window.onscroll or something, and unless you want to dig into the code of every library you're using you probably won't know why. But that's not what the author is arguing, and it has nothing to do with adding elements to the DOM via jQuery vs via lower level methods.
- symmet 14y agoThere are some points that I'd agree with in this post, but the framing is all wrong. The author begins the article saying that abstractions are fast (the DOM) and ends the article saying that abstractions are slow (jQuery). The native vs web argument has been beaten to death. It comes down to this: there is no perfect solution and everything has trade-offs (speed, quality, and cost). Use your brain and pick the solution that works best for the problem you are trying to solve. As much as web apps have replaced many things that may have previously been implemented as native apps on the desktop, there is still native development being done.
- skrebbel 14y agoI stopped reading when he said that he thought 10000 divs in 200 milliseconds was impressive. That was impressive on a 486 SX. The things that make people go "woa!" in a browser are, barring WebGL demos entirely made in shaders, completely not-impressive when compared to doing the same outside a browser. This is fine. The browser is expected to handle so many wildly varying use cases at once, it can't be top speed at all of them. But don't go around telling us that something that Firefox does on a 2Ghz quad core PC is amazing when the same has been done on an Amiga 500. The DOM is slow. It can be used to be fast enough for most purposes.
- amadeus 14y agoAgreed. The DOM is incredibly slow, and his example is so asinine. What is the use case for generating 2000 unstyled divs with one line of text? Try making that into a nice slick CSS list, maybe throw an image in each list item, with some title copy and supporting text. Perhaps you throw a bit of text shadow on it to create a nice beveled effect. Oh yeah, that 2000 divs per 200 milliseconds probably just turned into 10. Maybe even less, maybe 1 or 2 on a mobile browser.
- sophacles 14y agoThis is really taking things out of context. The DOM might be slow compared to your Amiga, but the statement TFA is talking about is within the context of web browsers.
- furyofantares 14y agoThat bothered me too, but if you had read further I think you would have found the introduction misleading. The rest of the rant isn't really about DOM vs native, it's about good DOM code vs bad DOM code.
- NinjaWarrior 14y agoYes, from the viewpoint of a game developer, the DOM is extremely, painfully, awfully, ridiculously slow and completely useless other than static HUDs. With the DOM, we can move only hundreds of sprites at 60 fps (on the latest Core i7!). HTML5 Canvas can achieve thousands but it's also far from native (and the function of Canvas is very poor). WebGL can gain acceptable performance in many situations, but there is still much overhead. I suspect today's most web developers don't know the true performance of computers they are actually using.
- dsego 14y agoMaybe the DOM isn't, but browsers still are for more complex & animated UIs. And worse of all it rally depends on the browser. I was surprised that safari is still a lot better than chrome with smooth css animations, Chrome just chokes when there are larger images: http://stackoverflow.com/questions/15323228/css-transition-in-chrome-stops-or-is-jerky-while-an-image-is-being-rendered http://stackoverflow.com/questions/15323228/css-transition-i...
- nawitus 14y ago>Look: http://jsfiddle.net/YNxEK/ http://jsfiddle.net/YNxEK/. Ten THOUSAND divs in about 200 milliseconds. You call that impressive on 2013? My laptop can sort a million numbers in the times you can create a mere 10k objects. >using JavaScript, render the whole thing in about 100 milliseconds. That's not fast enough. 100ms is perceptible. Websites should render instantly, and 100ms is on top of everything else.
- mrgreenfur 14y agoI'm not sure what the guys attitude is, but I appreciate him pointing out those sweet JS functions that I'd been using jquery for!
- sergiotapia 14y agoMeh. To be honest I'll take the 800ms jquery approach and get home quicker rather than using plain old javascript to shave of 600ms off a function. For 99% of the projects out there, jQuery is fast enough and it's productivity boosts outweigh any performance costs.
- _pmf_ 14y ago"I have use cases different from yours. You must be wrong and/or stupid."
- ender7 14y agoI was a little surprised to hear "use document.createElement, it's faster than innerHTML" since the conventional wisdom was exactly the opposite a few years ago. Someone has already written a decent JSPerf to test this out: http://jsperf.com/innerhtml-vs-createelement-test/16 http://jsperf.com/innerhtml-vs-createelement-test/16 (see also http://jsperf.com/innerhtml-vs-createelement-test/4 http://jsperf.com/innerhtml-vs-createelement-test/4 for a slightly deeper dive) Based on the Browserscope results (and my own testing), it seems that document.createElement is faster in Webkit but slower in everything else (Gecko, Trident). So, a bit of a wash there unless you're targeting mobile. That said, in my experience HTML (template) parsing isn't the main bottleneck to getting an app to that smooth 60fps feeling. Usually the big targets you want to focus on there are avoiding cascading reflows/repaints, using smoother animation technologies such as requestAnimationFrame or CSS transitions/animations, understanding how to trigger hardware acceleration and what its limits are, and keeping careful control of your CSS special effects (border radius, box-shadow, gradients, etc). I recommend checking out http://jankfree.com/ http://jankfree.com/ (especially the I/O talk) if you're interested. (edit: I don't really like the original article's vitriol, but he's right about a couple things. Manipulating your nodes outside of the DOM is much faster, although you don't need to be inside a DocumentFragment to do this (don't get me wrong; DocFrags are pretty useful). Also, yes, please don't keep running those jQuery selectors over and over again. Store the jQ object that the selector returns to you and just reuse that)
- nsxwolf 14y agoThis rant is just the latest incarnation of "Real Programmers don't use Pascal".
- jqueryin 14y agoI'm personally not a fan of the author's writing style; it comes across a arrogant. For a junior to mid level developer, one should be a bit more mild mannered. I poked around the resume.js file and was also taken aback by the very last line: //Yes, this is fully valid JavaScript. Run it in the Chrome Web inspector, Firebug or similar. Those who care to know if JS is valid already know at a quick glance. The preferred method of validation is JSHint or JSLint.
- korynunn 14y agoYeah that line doesn't make a lot of sense until you realise it was copied from here: http://korynunn.com/resume.docx http://korynunn.com/resume.docx
- LukeShu 14y agoNot to be a grammar Nazi, but here are some corrections: Paragraph 1, sentence 2: Capitalize "I" in "i would say" Paragraph 2, sentence 3: Capitalize "Chrome" Paragraph 2, sentence 4: Capitalize "Firefox" Paragraph 3, sentence 1: Should be "you're" in "your coding against the Dalvik"
- scragg 14y agoI was curious about the speed of jQuery selector versus querySelectorAll so I made a jsperf test. I realized people have done it already when trying to select a slug. When looking at the results, I noticed opera having a massive edge over the rest so I assumed it was doing some caching. Therefore, I created a random DOM for each test using the setup/teardown. http://jsperf.com/jquery-vs-queryselectorall-scragg http://jsperf.com/jquery-vs-queryselectorall-scragg
- jgalt212 14y agoyour results confirmed what I suspected, that using jQuery selectors is both performant and readable code. Ergo, his second point is probably advice best ignored. His appoint about using document fragments, or some equivalent thereof that resides outside the main DOM, is a good practice to follow when there are a large number of serial changes to the DOM that in effect are only one change to the user.
- anonymous185671 14y agothe web isn't down you are
- Millennium 14y agoI wouldn't go that far. The DOM really is slow, due to a number of tradeoffs made in the API design. But the DOM is meant for working with HTML (and XML) documents -displaying them, updating the display, and getting input from the user- and it's fast enough for that. If you're using the DOM for anything else, you're almost certainly doing something wrong. One of the first rules to being fast in a GUI of any sort, Web-based or otherwise, is simple: don't abuse the runtime. Objective-C's runtime isn't very pretty for performance either, which is why you use the provided APIs when you can. When you can't, you get the data out of the objects and into a more suitable format, work with them there, and put the result back into the objects for display. There were some truly egregious cases of runtime-abuse in the old days: the first OSX versions of OmniWeb come to mind. But the dev community eventually caught up. It's the same with the DOM. That's the thing about jQuery-abuse. jQuery is a very, very good hammer: an awesome tool for working with the DOM. The problem comes when people start to think that every problem looks like a nail: they start using the DOM for everything, including things that it's just plain not designed for. And it works, more or less; it just doesn't work well. That's not a problem with the framework. It's a problem with the user.
- bromagosa 14y agoYour page IS slow: http://i.imgur.com/Avqw4L5.png?1 http://i.imgur.com/Avqw4L5.png?1
- asmosoinio 14y agoSite seems to be down. Mirror from Coral cache: http://blog.korynunn.com.nyud.net/javascript/the-dom-isnt-slow-you-are/ http://blog.korynunn.com.nyud.net/javascript/the-dom-isnt-sl...
- underwater 14y agoGoogle text-only cache is working for me: http://webcache.googleusercontent.com/search?q=cache:blog.korynunn.com/javascript/the-dom-isnt-slow-you-are/&hl=en&strip=1 http://webcache.googleusercontent.com/search?q=cache:blog.ko...
- benhowdle89 14y agoWorst. Writing. Style. Ever. So condescending.
- tolmark12 14y agoA simple comparison of Dom selection vs Jquery selection[1] When selecting one DIV by id, I'm consistently getting: DOM - 0.08ish ms Jquery - 0.2ish ms I do have an app where every millisecond is critical. For this app I'm using raw dom selectors. However, most of the time, the convenience of jquery selectors outweigh these performance gains. [1] - http://jsfiddle.net/tolmark12/9R39R/ http://jsfiddle.net/tolmark12/9R39R/ (open console)
- smallegan 14y agoLet me guess. Your site isn't unavailable... I am?
- scottcanoni 14y agoThe DOM isn't slow, your website is. Zing!
- korynunn 14y agoHi there, I'm Kory. I'm not surprised to see a large amount of disagreement and anger, partly because it threw this post together pretty quickly and i probably didn't explain things as well as i could have, and partly because, well, a lot of people really just cant write fast web apps. In no particular order i would like to address a few things (most of which were addressed in the article if you read to the end..): 1. I never said "don't use jQuery". What I was trying to convey was "don't use jQuery stupidly". 2. I never said the DOM was the fastest part of the platform, obviously it isn't, in fact it is one of the slowest parts. But then, I wasn't comparing its speed to the rest of the platform, but rather to human perception. It doesn't matter if DOM manipulation is orders of magnitude slower than object manipulation, because it is easily fast enough to do pretty much anything, on pretty much any device, if you know what you are doing. 3. The fact that you read hacker news is a good sign that this post wasn't aimed at you. The post was a vent from the frustration of hearing 'The DOM is slow' as an excuse by people with no idea what they are talking about. It's a belief that is just accepted by many who have had difficulties with web development in the past, without any investigation as to what the actual issue is. One think I see people doing a LOT is DOM selection. I find the pattern poor generally. Think about the standard case for developing 'web apps'. 1. Build objects in a server that describe the application. 2. Build a massive string from said objects. 3. Send it over the intertubes. 4. Give it to a browser, which then parses said string, fixes any errors you almost certainly made, then creates DOM elements. 5. Insert said DOM elements into the document. 6. Wait untill all of this is done, then use a tree searching algorithm to find said objects using jQuery/querySelectorAll/whatever. 7. Manipulate said object. WAT. This seems a pointlessly convoluted pattern. Alternative: 1. Build some objects on the server that describe the application. 2. Send it over the intertubes (Which will be faster, because a description of an app is going to be smaller than every little bit of it being sent) 3. Let JavaScript create DOM directly. No parsing, just pure DOM API calls. >>>Keep a reference to important elements.<<< 4. Insert DOM into document. 5. Work directly with the DOM elements. No selecting, no string manipulation, just normal object manipulation. I look forward to the argument that ensues.
- korynunn 14y agoAlso, for those commenting on my blog being down, yeah I would expect that to be the case, its hosted on our crappy media center, behind a home internet connection, on a PC that has about 5 IIS apps and 3 Node apps. I never really expected to have more than maybe 5 concurrent connections.