框架设计前瞻

70 阅读2分钟

声明式编程和命令式编程的区别是什么呢?

命令式编程关注过程

//比如我们需要在div中加入hellowo rld文本 下面代表则详细的描述了这个需求的过程
const dom = document.querySelector("div")
dom.innerHTML = "hello world!"

声明式编程只关注结果

//比如我们在vue模板中需要展示一个message变量,我们并不关心它是怎么渲染到div标签当中的,而是在div标签中,渲染
指定文本而已。
<div>{{message}}</div>

命令式vs编程式

//比如还是为div中插入helloworld
div.innerText = "hello world" // 假如耗时为:1  

应该没有比以上代码更简单的了 然后我们来看声明式,声明式的代码为:

<div>{{ msg }}</div>  <!-- 耗时为:1 + n -->
<!-- 将 msg 修改为 hello world -->

那么:已知修改 text 最简单的方式是 innerText ****,所以说无论声明式的代码是如何实现的文本切换,那么它的耗时一定是 > 1 的,我们把它比作 1 + n(对比的性能消耗)

所以,由以上举例可知:命令式的性能 > 声明式的性能

可维护性

可维护性代表的维度非常多,但是通常情况下,所谓的可维护性指的是:对代码可以方便的 阅读、修改、删除、增加

// 命令式
// 1. 获取到第一层的 div
const divEle = document.querySelector('#app')
// 2. 获取到它的子 div
const subDivEle = divEle.querySelector('div')
// 3. 获取第三层的 p
const subPEle = subDivEle.querySelector('p')
// 4. 定义变量 msg
const msg = 'hello world'
// 5. 为该 p 元素设置 innerHTML 为 hello world
subPEle.innerHTML = msg
// 声明式
<div id="app">
  <div>
    <p>{{ msg }}</p>
  </div>
</div>

对于以上代码而言,声明式 的代码明显更加利于阅读,所以也更加利于维护。

所以,由以上举例可知:命令式的可维护性 < 声明式的可维护性

什么是运行时?

Vue 3源代码 中存在一个 runtime-core 的文件夹,该文件夹内存放的就是 运行时 的核心代码逻辑。

runtime-core 中对外暴露了一个函数,叫做 渲染函数 render

可以通过 render 代替 template 来完成 DOM 的渲染:

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://unpkg.com/vue@3.2.36/dist/vue.global.js"></script>
</head>

<body>
  <div id="app"></div>
</body>

<script>
  const { render, h } = Vue
  // 生成 VNode
  const vnode = h('div', {
    class: 'test'
  }, 'hello render')

  // 承载的容器
  const container = document.querySelector('#app')

  // 渲染函数
  render(vnode, container)
</script>

什么是编译时

Vue 中的编译时,更准确的说法应该是 编译器 的意思。它的代码主要存在于 compiler-core 模块下。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://unpkg.com/vue@3.2.36/dist/vue.global.js"></script>
</head>

<body>
  <div id="app"></div>
</body>

<script>
  const { compile, createApp } = Vue

  // 创建一个 html 结构
  const html = `
    <div class="test">hello compiler</div>
  `
  // 利用 compile 函数,生成 render 函数
  const renderFn = compile(html)

  // 创建实例
  const app = createApp({
    // 利用 render 函数进行渲染
    render: renderFn
  })
  // 挂载
  app.mount('#app')
</script>

</html>

对于编译器compiler而言,他会将vue中template中的内容编辑成一个render函数,然后通过运行时render挂载对应的dom,所以vue就是运行时+编译时的一个过程