vue2三种渲染方式其性能差异分析

本文分析了Vue2中template、h函数和JSX三种渲染方式的性能,通过渲染5000个div的实验,发现h函数和JSX在内存占用和渲染时间上优于template,其中JSX具有更好的可读性和维护性,推荐用于追求高性能的项目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

大多数前端开发者可能习惯了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。至于为什么会有如此大的差异,根据下面这张图获取就能知道答案。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值