Breaking the JavaScript Speed Limit with V8 - Google IO 2012
Breaking the JavaScript Speed Limit with V8 - Google IO 2012
The Optimization Checklist
- Be prepared before you have a problem
- Identify and understand the crux of your problem
- Fix what matters
What does “Be Prepared” mean for V8?
- Understand how V8 optimizes JavaScript
- Write code mindfully
- Learn your tools and how they can help you
Hidden Classes Make JavaScript Faster
- V8 internally creates hidden classes for objects at runtime
- Objects with the same hidden class can use the same optimized generated code
Avoid the speed trap
- 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 (e.g. > 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
- Optimizing compiler “bails-out” on functions with try {} catch {} blocks
- Avoid hidden class changes in functions after they are optimized
Double (type) Array Unboxing
- Array’s hidden class tracks element types
- Arrays containing only doubles are unboxed
- Unboxing causes hidden class change
- Careless manipulation of Arrays can cause extra work due to boxing and unboxing, initialize a mixed type array other than set items one by one
Monomorphic Better Than Polymorphic
- Operations are monomorphic if the hidden class is always the same
- Otherwise they are polymorphic