7 ms·
Javascript and CSS best practices for better performance
- hackermom 16y agoTo state the obvious: the JS performance advices this person gives won't necessarily apply the same to ALL JS engines. I wonder which specific browser and version he/she bases the advice on. (Why the heck do the kindergarten people of HN downvote this? It's a perfectly sensible question.)
- daleharvey 16y agoVery very few of these arent applicable to all javascript engines, most are a by product of the language itself. the only one that is specifically says "yes for ie"
- nixy 16y agoYou are correct. I work with JS engine implementations most people have never heard of. Performance is different between engine implementations, and so is availability of different ways of solving a task. Using the common browsers' best practice for performance doesn't always work for me. My favorite JS engine is the one implemented in the Evo browser. Among other things, it lacks support for arrays and for loops which makes development a tad interesting. And then we have the iPanel browser built for the Sunniwell set-top-box, in which you have no try/catch. Also, if you use more than five chained if/else, the browser will crash. However, this could be viewed as enforcing general programming best practices :)
- cema 16y agoQuote: it lacks support for arrays and for loops Wow. They still call it Javascript? Could you please point at the docs, to see what kind of language they offer? Thanks!
- geuis 16y ago#1 is completely wrong. Use of document fragments is much faster than innerHTML. This way your dom operations occur in memory and the results are pushed to the dom in one operation. Most of the rest of the tips are valid.
- webuiarchitect 16y agoNo Geuis. Setting innerHTML works faster than DOM methods. Please test.
- daleharvey 16y agoit isnt completely wrong, just slightly confusing. I am guessing he means using innerHTML over working on live dom nodes which are very expensive. documentfragments should definitely be worth mentioning though.
- kls 16y agoAlways fall back to core JavaScript whenever possible. Limit framework usage. Why, frameworks exist for a reason and keeps us from reinventing the wheel. Many times a contributor to a framework has labored to make his routine as efficient as possible on the broadest array of platforms. Many times we can forgo a lot of optimization work by using the framework rather than rolling our own.
- daleharvey 16y agoframeworks provide generic interfaces, a lot of the times they support wildly varying uses while you know exactly what you want to do $("#myid") vs document.getElementById("myid") for example, $() supports a vast amount of functionality.
- CoryMathews 16y agoThis article is about performance not ease of development. Frameworks are made to make development quicker and easier, but its at the cost of performance.
- boucher 16y agoGross generalization alert. True ever? Probably. True always? Absolutely certainly not.
- alexyim 16y agoRight. It depends on the framework too, jQuery is probably a good bet whereas a plugin built on top of them might not be. In any case, if you're concerned about performance, you should examine the source code of the framework anyways to see if it's doing anything unnecessary from what's required of your application.
- Kilimanjaro 16y agoAnd they are cached all over the web, try using google cdn whenever possible.
- subbu 16y agoI think he is referring to asset hosts in #20. Rails does it pretty easily. ActionController::Base.asset_host = "assets.example.com"
- webuiarchitect 16y agoYou are right, Subbu. Rails is nothing but common sense; it leaves developers only to do development and nothing else.
- JangoSteve 16y agoOr better yet, split assets over 4 asset subdomains: ActionController::Base.asset_host = Proc.new { |source| "assets#{source.hash % 4}.example.com" }
- ck2 16y agoThe problem with this list is some are micro-optimizations while others are rather important and dramatic, but they are all listed together in no particular order or weight.
- webuiarchitect 16y agoYes, it is a random list.
- FlemishBeeCycle 16y agoI hate articles that just make a bunch of assertions without any explanation as to _why_ or performance tests. If I'm earning a savings of < 1ms by making one choice over the other, it is probably more time efficient for me to simply not worry about it. > 8 But if you have multiple string concatenation, prefer pushing to an Array and then calling the join() method on it. This is particularly helpful while building HTML snippets. Depends on too many factors (browser, number of segments, segment length etc) to a be rule. Most of the time, the performance between this and += is going to be more or less the same. > 26 With AJAX, GET works faster than POST. So prefer GET unless request length is more than 2K; yes, you guessed it right - IE. Use GET or POST when you're supposed to not based on how much information you think you'll be sending. > 27. Go easy on scripted animations. What's easy? What's hard? > 30. Always fall back to core JavaScript whenever possible. Limit framework usage. It would be more prudent to _know_ your framework, and know when to not use it. IE (even in 9!) still doesn't implement indexOf - I can roll my own solution or use jQuery's inArray. Here's a better article http://www.slideshare.net/nzakas/speed-up-your-javascript http://www.slideshare.net/nzakas/speed-up-your-javascript
- webuiarchitect 16y agoNickolas Zakas' Slideshare presentation mainly covers the four areas of performance and goes deep into it, while my aim was to cover as many aspects as possible (not restricting it only to JavaScript) and add brief description wherever I could. Also, when we talk about performance, we usually talk about milliseconds - so if doing something shows even slightest improvement on at least one of the browser (e.g. accessing object properties by dot notation works faster on Safari and doesn't make difference on other browsers), it helps in keeping a watch on that practice. Even JSLint does the same.
- juliusdavies 16y ago#29 No Tables. How does that help performance? Sure on very large pages that might help, since the table usually won't render until the </table> has been sent, but maybe the better tip would be "avoid very large pages" (i.e. 100KB or more of HTML). DIV based layout also degrade if text in a single cell is very large, whereas Table based layout is robust against that. Also, I don't understand why <TABLE> is bad, but this is okay!?!?! <div class='table'> <div class='tr'> <div class='td'>1</div><div class='td'>2</div><div class='td'>3</div> </div> <div class='tr'> <div class='td'>a</div><div class='td'>b</div><div class='td'>c</div> </div> </div> Which is what DIV/FLOAT layout usually ends up becoming. If your DIV/FLOAT layout doesn't map to a structure like that, you're probably doing something wrong! Finally, has IE fixed the "we double the padding on floats" issue? Because float-driven layout with that bug is pretty hard, since IE will double your paddings while the other browsers don't. I do know that proudly espousing TABLE in a job interview can cost you the job. But aside from that TABLE is very effective for most layouts. I do avoid TABLE inside TABLE of course, that's a code smell, but top level TABLE is the right tool most of the time. Do anti-TABLE people also avoid Excel?
- webuiarchitect 16y agoUpdated the blog with some explanation on why TABLEs for layout is not a good idea. Please recheck.
- mayoff 16y agoSome of the advice is just plain wrong depending on your target platform. For example, on my iPad, iPhone 3G (not 3GS), and Safari 5.0 (6533.16)/Mac, using createElement/appendChild is consistently faster than using innerHTML. In Chrome 5.0.375.70/Mac, they are the same speed. In Firefox 3.6.3/Mac, naive createElement is slower, but using a DocumentFragment makes it as fast as innerHTML. My test case: http://dqd.com/~mayoff/timeDom.html http://dqd.com/~mayoff/timeDom.html
- interesse 16y agoPoor freshmen taking all of this for real. Ever heard of premature optimization?
- lhorie 16y agoThis author doesn't inspire much confidence when he says "A fellow reader just forwarded this link to me" when referring to Google Closure. Did he even try it out? Also, some things are pretty pointless (e.g. "#6 - no globals" doesn't do anything to improve performance), and other are poorly explained (e.g. "#13 - store local refs to out-of-scope vars" - what does that even mean?) He even has syntax errors (e.g. "#7 - var fullName +=", really?) and other oddities ("#28 - element.bind" What in the world is that?) The good points are largely regurgitation of stuff that is much better covered by Steve Souders, the Opera blog and other resources.
- webuiarchitect 16y agoThanks for all the valuable feedback. I have updated the post by adding little explanation to most of the points there to justify each concern. And have revised a couple of points. Please feel free to comment further. Please revisit http://www.webuiarchitect.com/30-best-practices-to-boost-your-web-applicati http://www.webuiarchitect.com/30-best-practices-to-boost-you... to see the changes.
- jaysoo 16y ago> #13 In any code block, store local references to out-of-scope variables. That doesn't even make sense. The for-loop block doesn't create a new scope, so it's perfectly valid to refer to the variable `a`. Plus, even if you create a new scope, you can still refer to `a` due to closure.
- webuiarchitect 16y agoWe are talking about performance optimization here; which means 'what will work faster' over conventional approaches. Every time the scripting engine doesn't find a variable in the local scope, it starts searching for it upwards until it reaches global namespace. And this, my friend, costs CPU cycles. Now consider this out-of-scope variable being used in a loop. Closure is a power JavaScript has given us to use it wisely; and not to misuse.
- jaysoo 16y agoIn the case of closure, yes you will take a small performance hit. But the example given is still invalid because the only scope present is the function-scope (for-loop doesn't create new scope). For example, if you ran the code below in FireBug you'll get the same results (minor variance aside). function foo() { var a = 0; for (var i=0, j=a; i<10000000; i++) { var x = j+i; } } function bar() { var a = 0; for (var i=0; i<10000000; i++) { var x = a+i; } } (function() { var start = new Date().getTime(), end; foo(); end = new Date().getTime(); console.log(end-start); })(); (function() { var start = new Date().getTime(), end; bar(); end = new Date().getTime(); console.log(end-start); })();
- webuiarchitect 16y agofor-loop does create a scope. In fact, every statement block is a scope in itself. In your examples, just change the value of variable 'a' to 100 or 1000 and you will see the difference.
- jaysoo 16y ago