今天下午在阅读Vue3,Component相关源码时,发现了这么一段注释。(源码地址:packages/runtime-core/src/componentProxy.ts
)缓存
This getter gets called for every property access on the render context during render and is a major hotspot. The most expensive part of this is the multiple hasOwn() calls. It's much faster to do a simple property access on a plain object, so we use an accessCache object (with null prototype) to memoize what access type a key corresponds to.性能
大体意思是以下:优化
在渲染期间,对渲染上下文进行访问时,hasOwn()
操做很昂贵。而在普通对象上进行属性访问的操做,速度会快不少。因此在Vue3中使用accessCache对象,对对象进行缓存。ui
那么Object.prototype.hasOwnProperty
操做是有多昂贵,值得尤大进行优化。我使用下面的代码,进行了实验。this
const obj = {
name: 'Natalie portman'
}
const accessCache = { ...obj }
const hasOwnProperty = Object.prototype.hasOwnProperty
const hasOwn = (val, key) => hasOwnProperty.call(val, key)
let start = new Date().getTime()
for (let i = 0; i < 5000000; i++) {
hasOwn(obj, 'name')
}
console.log(`duration: ${new Date().getTime() - start}`)
start = new Date().getTime()
for (let i = 0; i < 5000000; i++) {
accessCache.name
}
console.log(`duration: ${new Date().getTime() - start}`)
// log
// duration: 35
// duration: 4
复制代码
在进行500万次,读取属性操做时,二者的性能相差了大约9倍。spa
当Vue的组件树很大时,挂载的属性不少时。使用accessCache
对象,对Object.prototype.hasOwnProperty操做进行缓存,应该仍是颇有必要的。prototype
查询了相关资料,大体缘由以下:code
Chrome的V8引擎,会维护一个全局的缓存。一旦高速缓存被填充,它老是会在随后被重复命中。这意味着val[key]
属性查找,将始终在编译时处理,而不会进行运行时。component
而V8引擎不会对,hasOwnProperty
或者key in value
进行任何缓存,老是进入运行时。对象
👏欢迎你们指正。Vue3响应式数据源码,nextTick,watch,相对来讲很独立,看起来很轻松。可是看到到Component后,涉及的内容太多了,推动的很慢。