Daniel Clifford recently gave a great talk at Google I/O 2012 called “Breaking the JavaScript Speed Limit with V8”. In it he goes in depth to explain 13 simple optimizations you can do in your JavaScript code to help Chrome’s V8 JavaScript engine compile / run your JavaScript code faster. In the talk he gives a lot of great explanations as to what they are and why they help, but if you just want the quick and dirty list, here goes:
- Initialize all object members in constructor functions
- Always initialize object members in the same order
- Prefer numeric values that can be represented as 31-bit signed integers
- Use contiguous keys starting at 0 for Arrays
- Don’t pre-allocate large Arrays (>64K elements) to their maximum size, instead grow as you go
- Don’t delete elements in arrays, especially numeric arrays
- Don’t load uninitialized or deleted elements
- Initialize using array literals for small fixed-sized arrays
- Preallocate small arrays to correct size before using them
- Don’t store non-numeric values (objects) in numeric arrays
- Prefer monomorphic over polymorphic wherever possible
- Don’t use try {} catch {} blocks
- Avoid hidden class changes in functions after they are optimized
If you have time to check out the full video and/or slides I would highly recommend it. I know I for one will check back to the list often and am trying to watch for these gotchas in my code going forward.