前言
大多数前端开发者可能习惯了vue模板引擎的渲染方式,但是不知道你留意过没,template模式其内存占用是最高的,渲染时间也是最长的,对于大型应用来说,这是不能接受的。下面我们分析一下vue2三种渲染方式template、h函数、jsx其各自性能表现。
3种渲染方式比较
1、template
渲染5000个div,代码如下
<template>
<div>
<UserProfile v-for='item in list' :key='item' :name='item' />
</div>
</template>
<script>
import UserProfile from '../components/UserProfile'
export default {
name: 'Home',
components: { UserProfile },
data () {
return {
list: Array(5000)
.fill(null)
.map((_, idx) => 'Test' + idx)
}
},
beforeMount () {
this.start = Date.now()
},
mounted () {
console.log('用时:', Date.now() - this.start)
}
}
</script>
组件UserProfile代码如下
<template>
<div class="user-profile">{{name}}</div>
</template>
<script>
export default {
props: [ 'name' ],
data () {
return {}
},
methods: {}
}
</script>
chrome无痕模式下,内存和渲染时间表现
2、h函数
渲染5000个div,代码如下
<script>
import { myRender, } from '../libs/index'
export default {
name: 'Jsx',
components: {},
data () {
return {
list: Array(5000)
.fill(null)
.map((_, idx) => 'Test' + idx)
}
},
beforeMount () {
this.start = Date.now()
},
mounted () {
console.log('用时:', Date.now() - this.start)
},
render: function(h) {
return myRender(h, this)
}
}
</script>
函数myRender代码如下
export const myRender = (h, self) => {
return h('div', {}, [
self.list.map(item => {
return h('div', {
class: 'user-profile'
}, item)
})
])
}
chrome无痕模式下,内存和渲染时间表现
3、jsx
渲染5000个div,代码如下
<script>
import { myRender, } from '../libs/index'
export default {
name: 'Jsx',
components: {},
data () {
return {
list: Array(5000)
.fill(null)
.map((_, idx) => 'Test' + idx)
}
},
beforeMount () {
this.start = Date.now()
},
mounted () {
console.log('用时:', Date.now() - this.start)
},
render: function(h) {
return myRender(h, this)
}
}
</script>
函数myRender代码如下
export const myRender = (h, self) => {
return (
<div>
{
self.list.map(item => {
return <div className='user-profile' key={item}>{item}</div>
})
}
</div>
)
}
chrome无痕模式下,内存和渲染时间表现
结论
很明显h函数和jsx占用内存最低,渲染时耗也最低,但是h函数是比较底层的写法,不直观也难以维护,因此想要项目取得最好的性能,建议使用jsx。至于为什么会有如此大的差异,根据下面这张图获取就能知道答案。