1. Compilation stage
reviewVue2,We know that each component instance corresponds to a watcher instance, which will record the used data property as a dependency during component rendering. When the dependency changes and triggers the setter, the watcher will be notified, thereby re-rendering the associated component.
<template>
<div id="content">
<p class="text">node</p>
<p class="text">node</p>
<p class="text">{{ message }}</p>
<p class="text">node</p>
</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
You can see that there is only one dynamic node inside the component, and the remaining bunch of them are static nodes, so many diffs and traversals here are actually unnecessary, resulting inperformancewaste
therefore,Vue3During the compilation stage, further optimization was made. The main ones are as follows:
- Diff algorithm optimization
- Static boost
- Event listening cache
- SSR optimization
4.1 diffAlgorithm optimization
vue3 adds static marking compared to vue2 in the diff algorithm
Regarding this static marker, its function is to add a flag mark where changes occur. Next time the changes occur, it will be compared.
4.2 Static boost
In Vue3, elements that do not participate in the update will be statically upgraded, and will only be created once and will be reused directly during rendering.
This eliminates duplicate creation nodes, and large applications will benefit from this change, eliminate duplicate creation operations, and optimize the memory usage during runtime
4.3 Event listening cache
By default, the binding event behavior is consideredDynamic binding, so I will track its changes every time
After the above discovery is turned on, there is no static marker. That is to say, use the diff algorithm next time
4.4 SSR optimization
When the static content is large enough to a certain level, a static will be generated on the client using the createStaticVNode methodnode, These static nodes will be directly innerHtml, so there is no need to create an object and then render it according to the object.
2. Source code volume
Compared with Vue2, Vue3 has become smaller in overall volume. In addition to removing some uncommon APIs, what is more important is that Tree shanking any function, such as ref, reavtived, computed, etc., is only packaged when used. Unused modules are shaken off, and the overall volume of packaged becomes smaller.
3. Responsive system
In vue2, defineProperty is used to hijack the entire object, and then iterate through all properties in depth, add getters and setters to each property, implement responsiveness
vue3 uses proxy to rewritten the responsive system, because proxy can listen to the entire object, so there is no need for deep traversal.
- You can listen to the addition of dynamic attributes
- You can listen to the index and array length attributes of an array
- Can listen to delete attributes