9 ms·
V8 Optimization Killers
- btown 12y agoAn excellent overview! A bit worrying that using an object as a hash table and iterating over its keys using ForIn would prevent optimization - I had always thought that this was a common use case that would be well-supported by the optimizer! I suppose in that case, if you need fast reads of all keys and can afford slower writes, you could maintain an array of the keys at insertion time and just loop through that?
- phpnode 12y ago`for ... in` is a relatively slow construct anyway, the faster option (a lot more verbose) is: var keys = Object.keys(obj), length = keys.length, key, i; for (i = 0; i < length; i++) { key = keys[i]; } While this is not exactly the same as for..in, it usually behaves how you'd expect and is significantly faster for a couple of reasons: 1. In a for..in loop the engine must keep track of the keys already iterated over, whereas in the fast version we can simply increment a counter and do a fast array lookup. 2. It's possible to add properties to the object that you're iterating within the body of the for..in statement, and these will be iterated too. Doing such a thing is obviously very rare but it's the kind of edge case the JS engine must keep track of.
- Alphasite_ 12y agoIs that (#2) defined behaviour, or is it undefined? Because iirc, other languages disallow it for similar reasons.
- gsnedders 12y agoAdding properties is undefined in ES5 and I believe defined in ES6. Deleting properties is guaranteed to not break iteration and deleting an as-of-yet unvisited property causes it to never be visited.
- general_failure 12y agoObject.keys() does not need to malloc() ?
- kipple 12y agoIs a plain for loop with a counter significantly faster than a forEach? With Object.keys I've been enjoying the simplicity of statements like Object.keys(obj).forEach(function (key) { console.log(obj[key]); }); but does that hamstring my performance?
- bzbarsky 12y agoYour mileage will vary depending on the browser. If you really care (as in profiling identified this as a hotspot) you should measure the alternatives you're considering. But note that in your specific case chances are the cost of a bunch of console.log() calls completely swamps the cost of either a for loop or a forEach call. console.log() has _incredibly_ complicated behavior.
- ekmartin 12y agoA native counter for-loop will always be faster: http://jsperf.com/angular-foreach-vs-native-for-loop/13 http://jsperf.com/angular-foreach-vs-native-for-loop/13
- kevingadd 12y agoKeys is an alloc. That is not 'faster'.
- killercup 12y agoTitle should probably be "V8 Optimization Killers".
- Touche 12y agoI'm really sick of these recent JavaScript performance related posts that only talk about V8.
- hawkice 12y agoI think the general idea is that asm.js is both well understood and not something a human should ever generate, so why would anyone but a transpiler writer care?
- Touche 12y agoI don't know why you are bring up asm.js.
- arcatek 12y agoI'm not sure why you're talking about asm.js (I guess you're implying that asm.js is the only Gecko-specific optimization?), but I just want to note that I find it pretty hard to find good documentation about how to code with it. The "not something a human should ever generate" doesn't seem like a right statement : before a transpiler can generate this kind of code, a human has to understand it.
- simonster 12y agoHere's a page with some performance tips for both V8 and SpiderMonkey: https://github.com/sq/JSIL/wiki/JavaScript-Performance-For-Madmen https://github.com/sq/JSIL/wiki/JavaScript-Performance-For-M.... Unfortunately given the pace at which JS engines move it may be slightly out of date.
- rplnt 12y agoIt's like searching for any js problem on SO and almost every single question containing top answer with response along the lines "use jquery".
- binarymax 12y agoReally great! Some notes that popped out for me are that to always cache the .length property for any array or arguments: function doesntLeakArguments() { var args = new Array(arguments.length); for(var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } return args; } becomes: function doesntLeakArguments() { var len = arguments.length; var args = new Array(len); for(var i = 0; i < len; ++i) { args[i] = arguments[i]; } return args; } And also, if you've got a switch statement with more than 128 cases, you've probably got bigger problems on your hands than v8 optimizations. I see some things in here that I can start switching to immediately for some of my node modules.
- phpnode 12y agoThe article is "optimisation killers", you're right about caching the array length lookup check being faster, but it doesn't kill V8's ability to optimise functions like the rest of the examples do
- pdw 12y agoHuge switches are common in the inner loop of emulators and interpreters. They tend to end up with a 256-case switch to handle the next byte in the instruction stream.
- binarymax 12y agoI understand that use case, but in my opinion it would be much cleaner (and speculating faster) to have an 256-slot array...and routing with opcodes[byte.charCodeAt(0)](); or something similar.
- arcatek 12y agoFunction calls are expensive if they are not optimized. However, the same is true for switch/case trees, and even for JIT'd code (dynamically created functions) ... In the Javascript world, "Your Mileage May Vary" truly is a motto.
- 12y ago
- iMark 12y agoUseful stuff. Does anyone have similar information for other javascript engines?
- kateperry 12y agomy roomate's sister-in-law earned $14851 last month. she is getting paid on the laptop and moved in a $499100 house. All she did was get blessed and put to work the clues exposed on this web site ,,,,,,,, ,,,,,,,, WWW.MAX43.COM
- kateperry 12y agohi..............
- kateperry 12y ago@@@@@@@@@@@@@@@@@@@@@@@@@@@
- ttty 12y agoWhich is better `undefinedVar === void 0` or `typeof undefinedVar === 'undefined'`? here says: http://www.2ality.com/2013/04/check-undefined.html http://www.2ality.com/2013/04/check-undefined.html void 0 is safe.
- ekmartin 12y agoI think minifiers use the former because it's shorter, and thus requires less space.
- 12y ago
- d0ugie 12y agoMy team's developers, who are in a Firefox-only setting (so no V8 to consider), use every optimization/squishing trick they can find on github - grunt, browserify, uglifyjs etc - thinking that the smaller the number of javascript resources and the smaller those files are the faster the pages will not just download but also render. Is it probable that SpiderMonkey and other engines suffer from forms of this deoptimization hell when rendering? And would it be a safe guess that whatever mod_pagespeed does to a page's javascript resources is less likely to result in this hell than these other tools? Thanks.
- arcatek 12y agoThe only size-related optimization that I can think of is that V8 doesn't inline functions (but does optimize them) when they are more than X characters long, comments included. I'm not sure about SpiderMonkey, but they may very well use this kind of optimization too. However, I would guess that Uglifying files should not increase execution speed for any noticeable amount.
- driverdan 12y agoIt's a good question but minification shouldn't cause runtime performance issues. Keep in mind that these are mostly micro optimizations when running outside a large loop. If you go from 1 mil ops per sec to 20 mil ops per sec your user won't see a difference unless the code is being run many times over.
- kevingadd 12y agoI'm not aware of any common minification techniques that hurt performance. They generally improve parser performance and reduce memory usage (less memory spent on line-ending data and script sources, for example)
- netcraft 12y agoI wonder if there is any way to check the optimization status in the browser? It would be awesome to have a chrome audit that parsed through all of the functions in a js file and told you the optimization status of each and why.
- deleted 12y ago[deleted]
- wpears 12y agoNot the friendliest program but http://mrale.ph/irhydra/1/ http://mrale.ph/irhydra/1/ can display all sorts of intermediate representations spit out by v8
- PSeitz 12y agoI created a jsperf to measure a hashtable-like object with for-in/Objekt.keys The performance differs only with 50%, I expected more actually. Am I doing something wrong? http://jsperf.com/for-in-with-hashtable-like-object http://jsperf.com/for-in-with-hashtable-like-object
- autnecare 12y agoI guess it depends on what you're intent is; http://jsperf.com/for-in-with-hashtable-like-object/4 http://jsperf.com/for-in-with-hashtable-like-object/4
- PSeitz 12y agoThe article states "Code compiled by the optimizing compiler can easily be, say, 100x faster than the code generated by the generic compiler" So expected a quite more than a factor of 2 ...
- kretor 12y agoInstead of avoiding all those optimization killers, a much more higher impact approach is to fix this in the V8 project. You not only make your own code faster, you make thousands if not millions of pieces of code faster.
- _greim_ 12y agoI was wondering this too. I expect/hope the answer would be "we're working on it" in most cases, but I worry it would be "it simply isn't possible" in some or most scenarios.
- _greim_ 12y agoWhich of these (if any) are purely incidental to the current state of the V8 project, rather than being inherently insurmountable problems for JS optimization? In other words, if I memorize this particular list, what subset of my knowledge may become obsolete in a few months or years?
- bzbarsky 12y agoThe try/catch bit is definitely incidental to the current state of V8. Other JITs (e.g. SpiderMonkey) will happily handle try/catch.
- olliej 12y ago|with| makes reasoning about function behaviour extremely difficult, take: var x = 5; something.propertyOnSomething = 5 with(something) { x += propertyOnSomething } alert(x); // What is the value of x? eval() causes problems as it can introduce new variables into the local scope making it logically difficult to reason about program behaviour subsequent to the eval(), e.g. function f(x) { eval(something); return Math.sqrt(x); } What is the result of f(9)? It is possible to set things up to make these not catastrophically harm performance, but the question is whether you would rather the engineers working on these engines make uncommon (and arguably bad) things common, or make normal and frequent code fast. Any time spent working on making uncommon things fast is time not spent making other things fast.
- azakai 12y ago> if I memorize this particular list Please don't memorize this list. It's just for one JS engine among several, all of which are changing rapidly. For example Apple just shipped FTL, an LLVM-based JIT for Safari (so any list for Safari would have just been largely obsoleted).
- sheetjs 12y ago> It's just for one JS engine among several If you are writing code for nodejs, none of the other engines are relevant. If the overwhelming majority of your users are using chrome, then v8-specific optimizations aren't a bad idea. On the issue of the list, most of the guidelines here apply here and in every other engine. For example, I doubt a future JS engine can optimize `arguments` abuse while preserving ES5 semantics.
- deleted 12y ago[deleted]