[V8] Object shapes & Hidden classes

发布时间 2023-11-08 03:00:55作者: Zhentiw

  • When you create a object, in V8, it creates a hidden class to repesent the object shape.
  • Two different objects with same object shape might share the same hidden class
  • Any difference in object (prop order, more or less props) will result two different hidden class
  • Keep a low number of hidden class can help with V8 performance.

 

Ideas:

  1. Always using factory function to create object. so that can keep the object shape the same everytime.
  2. Don't split object creation into multi steps, it will force V8 to create another hidden class
  3. Define all the possible props for object in one go, mark some props as undefined and change value later
  4. In Typescript, for an object {name: string, company?: string} or {name: string, company: string | undefined }, which one to choose?
    • In most case they are the same
    • But consider hidden class {name: string, company: string | undefined }will be prefer approach
    • {name: string, company: string | undefined }: means that company should be there, but can be undefined
    • {name: string, company?: string}: means that company may not exist at all
    • Different means might results a difference in V8 preformance in the end.