国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

React系列 --- virtualdom diff算法實現分析(三)

sunsmell / 1954人閱讀

摘要:所以只針對同層級節點做比較,將復雜度的問題轉換成復雜度的問題。

React系列

React系列 --- 簡單模擬語法(一)
React系列 --- Jsx, 合成事件與Refs(二)
React系列 --- virtualdom diff算法實現分析(三)
React系列 --- 從Mixin到HOC再到HOOKS(四)
React系列 --- createElement, ReactElement與Component部分源碼解析(五)
React系列 --- 從使用React了解Css的各種使用方案(六)

完整代碼可查看virtualdom-diff

渲染DOM

經歷過PHP模板開發或者JQuery的洗禮的人都知道,它們實現重新渲染采用最簡單粗暴的辦法就是重新構建DOM替換舊DOM,問題也很明顯

性能消耗高

無法保存狀態(聚焦,滾動等)

我們先看看創建一個元素所包含的實例屬性有多少個

</>復制代碼

  1. const div = document.createElement("div");
  2. let num = 0;
  3. for (let k in div) {
  4. num++;
  5. }
  6. console.log(num); // 241

然后瀏覽器根據CSS規則查找匹配節點,計算合并樣式布局,為了避免重新計算一般瀏覽器會保存這些數據.但這是整個過程下來依然會耗費大量的內存和 CPU 資源.

Virtual DOM

實際也是操作Dom樹進行渲染更新,但是它只是針對修改部分進行局部渲染,將影響降到最低,雖然實現方式各有不同,但是大體步驟如下:

用Javascript對象結構描述Dom樹結構,然后用它來構建真正的Dom樹插入文檔

當狀態發生改變之后,重新構造新的Javascript對象結構和舊的作對比得出差異

針對差異之處進行重新構建更新視圖

無非就是利用Js做一層映射比較,操作簡單并且速度遠遠高于直接比較Dom樹

基礎工具函數

無非就是一些類型判斷,循環遍歷的簡化函數

</>復制代碼

  1. function type(obj) {
  2. return Object.prototype.toString.call(obj).replace(/[objects|]/g, "");
  3. }
  4. function isArray(list) {
  5. return type(list) === "Array";
  6. }
  7. function isObject(obj) {
  8. return type(obj) === "Object";
  9. }
  10. function isString(str) {
  11. return type(str) === "String";
  12. }
  13. function isNotEmptyObj(obj) {
  14. return isObject(obj) && JSON.stringify(obj) != "{}";
  15. }
  16. function objForEach(obj, fn) {
  17. isNotEmptyObj(obj) && Object.keys(obj).forEach(fn);
  18. }
  19. function aryForEach(ary, fn) {
  20. ary.length && ary.forEach(fn);
  21. }
  22. function setAttr(node, key, value) {
  23. switch (key) {
  24. case "style":
  25. node.style.cssText = value;
  26. break;
  27. case "value":
  28. var tagName = node.tagName || "";
  29. tagName = tagName.toLowerCase();
  30. if (tagName === "input" || tagName === "textarea") {
  31. node.value = value;
  32. } else {
  33. // if it is not a input or textarea, use `setAttribute` to set
  34. node.setAttribute(key, value);
  35. }
  36. break;
  37. default:
  38. node.setAttribute(key, value);
  39. break;
  40. }
  41. }
  42. function toArray(data) {
  43. if (!data) {
  44. return [];
  45. }
  46. const ary = [];
  47. aryForEach(data, item => {
  48. ary.push(item);
  49. });
  50. return ary;
  51. }
  52. export {
  53. isArray,
  54. isObject,
  55. isString,
  56. isNotEmptyObj,
  57. objForEach,
  58. aryForEach,
  59. setAttr,
  60. toArray
  61. };

相關代碼可以查看util.js

Javascript對象結構描述

我之前講JSX的時候舉過這么個例子,然后我們就以這個來實現效果吧

</>復制代碼

  1. 123456

</>復制代碼

  1. "use strict";
  2. React.createElement("div", {
  3. className: "num",
  4. index: 1
  5. }, React.createElement("span", null, "123456"));

創建一個Element類負責將Javascript對象結構轉換為Dom樹結構

</>復制代碼

  1. import {
  2. isObject,
  3. isString,
  4. isArray,
  5. isNotEmptyObj,
  6. objForEach,
  7. aryForEach
  8. } from "./util";
  9. import { NOKEY } from "./common";
  10. class Element {
  11. constructor(tagName, props, children) {
  12. // 解析參數
  13. this.tagName = tagName;
  14. // 字段處理,可省略參數
  15. this.props = isObject(props) ? props : {};
  16. this.children =
  17. children ||
  18. (!isNotEmptyObj(this.props) &&
  19. ((isString(props) && [props]) || (isArray(props) && props))) ||
  20. [];
  21. // 無論void后的表達式是什么,void操作符都會返回undefined
  22. this.key = props ? props.key : void NOKEY;
  23. // 計算節點數
  24. let count = 0;
  25. aryForEach(this.children, (item, index) => {
  26. if (item instanceof Element) {
  27. count += item.count;
  28. } else {
  29. this.children[index] = "" + item;
  30. }
  31. count++;
  32. });
  33. this.count = count;
  34. }
  35. render() {
  36. // 根據tagName構建
  37. const dom = document.createElement(this.tagName);
  38. // 設置props
  39. objForEach(this.props, propName =>
  40. dom.setAttribute(propName, this.props[propName])
  41. );
  42. // 渲染children
  43. aryForEach(this.children, child => {
  44. const childDom =
  45. child instanceof Element
  46. ? child.render() // 如果子節點也是虛擬DOM,遞歸構建DOM節點
  47. : document.createTextNode(child); // 如果字符串,只構建文本節點
  48. dom.appendChild(childDom);
  49. });
  50. return dom;
  51. }
  52. }
  53. // 改變傳參方式,免去手動實例化
  54. export default function CreateElement(tagName, props, children) {
  55. return new Element( tagName, props, children );
  56. }

新建示例,調用方式如下

</>復制代碼

  1. // 1. 構建虛擬DOM
  2. const tree = createElement("div", { id: "root" }, [
  3. createElement("h1", { style: "color: blue" }, ["Tittle1"]),
  4. createElement("p", ["Hello, virtual-dom"]),
  5. createElement("ul", [
  6. createElement("li", { key: 1 }, ["li1"]),
  7. createElement("li", { key: 2 }, ["li2"]),
  8. createElement("li", { key: 3 }, ["li3"]),
  9. createElement("li", { key: 4 }, ["li4"])
  10. ])
  11. ]);
  12. // 2. 通過虛擬DOM構建真正的DOM
  13. const root = tree.render();
  14. document.body.appendChild(root);

運行之后能正常得出結果了,那么第一步驟算是完成了,具體還有更多不同類型標簽,對應事件狀態先略過.

界面如圖

Javascript結構如圖

結構原型如下

相關代碼可以查看element.js

diff算法

這是整個實現里面最關鍵的一步,因為這決定了計算的速度和操作Dom的數量

我們創建新的Dom樹作對比

</>復制代碼

  1. // 3. 生成新的虛擬DOM
  2. const newTree = createElement("div", { id: "container" }, [
  3. createElement("h1", { style: "color: red" }, ["Title2"]),
  4. createElement("h3", ["Hello, virtual-dom"]),
  5. createElement("ul", [
  6. createElement("li", { key: 3 }, ["li3"]),
  7. createElement("li", { key: 1 }, ["li1"]),
  8. createElement("li", { key: 2 }, ["li2"]),
  9. createElement("li", { key: 5 }, ["li5"])
  10. ])
  11. ]);

Javascript結構如圖

tree diff

傳統 diff 算法的復雜度為 O(n^3),但是一般Dom跨層級的情況是非常少見的。所以React 只針對同層級Dom節點做比較,將 O(n^3) 復雜度的問題轉換成 O(n) 復雜度的問題。

比較大的問題就是當節點跨層級移動并不會進行移動而是直接替換整個節點,所以切記這點性能問題

component diff

某個組件發生變化,會導致自其從上往下整體替換

同一類型組件會進行Virtual DOM進行比較

React提供了一個shouldComponentUpdate決定是否更新

盡可能將動態組件往底層節點遷移,有利于提高性能

element diff

元素操作無非就是幾種,我們定義幾個類型做狀態標記

</>復制代碼

  1. const REPLACE = "replace";
  2. const REORDER = "reorder";
  3. const PROPS = "props";
  4. const TEXT = "text";
  5. const NOKEY = "no_key"
  6. export {
  7. REPLACE,
  8. REORDER,
  9. PROPS,
  10. TEXT,
  11. NOKEY
  12. }

其中NOKEY就是專門給那些沒有定義key的組件做默認,React對同一層級的同組子節點,添加唯一 key 進行區分進行位移而不是直接替換,這點對于整體性能尤為關鍵

我們首先針對不同類型做些區分處理

</>復制代碼

  1. import { isString, objForEach, aryForEach, isNotEmptyObj } from "./util";
  2. import { REPLACE, REORDER, PROPS, TEXT } from "./common";
  3. import listDiff from "list-diff2";
  4. /**
  5. *
  6. * @param {舊Dom樹} oTree
  7. * @param {新Dom樹} nTree
  8. * 返回差異記錄
  9. */
  10. function diff(oTree, nTree) {
  11. // 節點位置
  12. let index = 0;
  13. // 差異記錄
  14. const patches = {};
  15. dfsWalk(oTree, nTree, index, patches);
  16. return patches;
  17. }
  18. function dfsWalk(oNode, nNode, index, patches) {
  19. const currentPatch = [];
  20. // 首次渲染
  21. if (nNode === null) return;
  22. // 都是字符串形式并且不相同直接替換文字
  23. if (isString(oNode) && isString(nNode)) {
  24. oNode !== nNode &&
  25. currentPatch.push({
  26. type: TEXT,
  27. content: nNode
  28. });
  29. // 同種標簽并且key相同
  30. } else if (oNode.tagName === nNode.tagName && oNode.key === nNode.key) {
  31. // 至少一方有值
  32. if (isNotEmptyObj(oNode.props) || isNotEmptyObj(nNode.props)) {
  33. // 計算props結果
  34. const propsPatches = diffProps(oNode, nNode);
  35. // 有差異則重新排序
  36. propsPatches &&
  37. currentPatch.push({
  38. type: PROPS,
  39. props: propsPatches
  40. });
  41. }
  42. // children對比
  43. if (
  44. !(!isNotEmptyObj(nNode.props) && nNode.props.hasOwnProperty("ignore"))
  45. ) {
  46. (oNode.children.length || nNode.children.length) &&
  47. diffChildren(
  48. oNode.children,
  49. nNode.children,
  50. index,
  51. patches,
  52. currentPatch
  53. );
  54. }
  55. } else {
  56. // 都不符合上面情況就直接替換
  57. currentPatch.push({ type: REPLACE, node: nNode });
  58. }
  59. // 最終對比結果
  60. currentPatch.length && (patches[index] = currentPatch);
  61. }

新舊節點的props屬性比較

</>復制代碼

  1. /**
  2. *
  3. * @param {舊節點} oNode
  4. * @param {新節點} nNode
  5. */
  6. function diffProps(oNode, nNode) {
  7. let isChange = false;
  8. const oProps = oNode.props;
  9. const nProps = nNode.props;
  10. // 節點屬性記錄
  11. const propsPatched = {};
  12. // 替換/新增屬性
  13. objForEach(oProps, key => {
  14. if (nProps[key] !== oProps[key] || !oProps.hasOwnProperty(key)) {
  15. !isChange && (isChange = true);
  16. propsPatched[key] = nProps[key];
  17. }
  18. });
  19. return !isChange ? null : propsPatched;
  20. }

新舊節點的子元素對比

</>復制代碼

  1. /**
  2. * 同級對比
  3. * @param {*} oChildren
  4. * @param {*} nChildren
  5. * @param {*} index
  6. * @param {*} patches
  7. * @param {*} currentPatch
  8. */
  9. function diffChildren(oChildren, nChildren, index, patches, currentPatch) {
  10. // 得出相對簡化移動路徑
  11. const diffs = listDiff(oChildren, nChildren, "key");
  12. // 保留元素
  13. nChildren = diffs.children;
  14. // 記錄排序位移
  15. diffs.moves.length &&
  16. currentPatch.push({ type: REORDER, moves: diffs.moves });
  17. // 深度遍歷
  18. let leftNode = null;
  19. let currentNodeIndex = index;
  20. aryForEach(oChildren, (_item, _index) => {
  21. const nChild = nChildren[_index];
  22. currentNodeIndex =
  23. leftNode && leftNode.count
  24. ? currentNodeIndex + leftNode.count + 1
  25. : currentNodeIndex + 1;
  26. _item !== nChild && dfsWalk(_item, nChild, currentNodeIndex, patches);
  27. leftNode = _item;
  28. });
  29. }

深度遍歷的原型圖如下

其中的listDiff來自于list-diff,能通過關鍵屬性獲得最小移動量,moves就是給第三步更新視圖做鋪墊指示,官方介紹如下

</>復制代碼

  1. Diff two lists in time O(n). I The algorithm finding the minimal amount of moves is Levenshtein distance which is O(n*m). This algorithm is not the best but is enougth for front-end DOM list manipulation.

This project is mostly influenced by virtual-dom algorithm.

調用對比方式

</>復制代碼

  1. // 4. 比較兩棵虛擬DOM樹的不同
  2. const patches = diff(tree, newTree);

得出差異如下

相關代碼可以查看diff.js

更新視圖

進行深度遍歷

</>復制代碼

  1. import {
  2. isString,
  3. isObject,
  4. objForEach,
  5. aryForEach,
  6. setAttr,
  7. toArray
  8. } from "./util";
  9. import { REPLACE, REORDER, PROPS, TEXT, NOKEY } from "./common";
  10. function patch(node, patches) {
  11. const walker = { index: 0 };
  12. dfsWalk(node, walker, patches);
  13. }
  14. // 深度遍歷更新
  15. function dfsWalk(node, walker, patches) {
  16. const currentPatches = patches[walker.index];
  17. node.childNodes &&
  18. aryForEach(node.childNodes, item => {
  19. walker.index++;
  20. dfsWalk(item, walker, patches);
  21. });
  22. currentPatches && applyPatches(node, currentPatches);
  23. }

針對不同標志做對應處理

</>復制代碼

  1. // 更新類型
  2. function applyPatches(node, currentPatches) {
  3. aryForEach(currentPatches, item => {
  4. switch (item.type) {
  5. case REPLACE:
  6. const nNode = isString(item.node)
  7. ? document.createTextNode(item.node)
  8. : item.node.render();
  9. node.parentNode.replaceChild(nNode, node);
  10. break;
  11. case REORDER:
  12. reorderChildren(node, item.moves);
  13. break;
  14. case PROPS:
  15. setProps(node, item.props);
  16. break;
  17. case TEXT:
  18. if (node.textContent) {
  19. // 使用純文本
  20. node.textContent = item.content;
  21. } else {
  22. // 僅僅對CDATA片段,注釋comment,Processing Instruction節點或text節點有效
  23. node.nodeValue = item.content;
  24. }
  25. break;
  26. default:
  27. throw new Error("Unknown patch type " + item.type);
  28. }
  29. });
  30. }

先說簡單的屬性替換

</>復制代碼

  1. // 修改屬性
  2. function setProps(node, props) {
  3. objForEach(props, key => {
  4. if (props[key] === void NOKEY) {
  5. node.removeAttribute(key);
  6. } else {
  7. setAttr(node, key, props[key]);
  8. }
  9. });
  10. }

最后就是列表渲染

</>復制代碼

  1. // 列表排序渲染
  2. function reorderChildren(node, moves) {
  3. const staticNodeList = toArray(node.childNodes);
  4. const maps = {};
  5. aryForEach(staticNodeList, node => {
  6. // Element
  7. if (node.nodeType === 1) {
  8. const key = node.getAttribute("key");
  9. key && (maps[key] = node);
  10. }
  11. });
  12. aryForEach(moves, move => {
  13. const index = move.index;
  14. // 0:刪除 1:替換
  15. if (move.type === 0) {
  16. // 找到對應節點刪除
  17. staticNodeList[index] === node.childNodes[index] &&
  18. node.removeChild(node.childNodes[index]);
  19. staticNodeList.splice(index, 1);
  20. } else if (move.type === 1) {
  21. let insertNode;
  22. if (maps[move.item.key]) {
  23. // 刪除并返回節點
  24. insertNode = node.removeChild(maps[move.item.key]);
  25. // 獲取刪除節點位置
  26. staticNodeList.splice(Array.prototype.indexOf.call(node.childNodes, maps[move.item.key]), 1);
  27. } else {
  28. // 創建節點
  29. insertNode = isObject(move.item)
  30. ? move.item.render()
  31. : document.createTextNode(move.item);
  32. }
  33. // 同步staticNodeList信息
  34. staticNodeList.splice(index, 0, insertNode);
  35. // 操作Dom
  36. node.insertBefore(insertNode, node.childNodes[index] || null);
  37. }
  38. });
  39. }
  40. export default patch;

當這一步完成以后我們可以直接應用查看效果

</>復制代碼

  1. // 4. 比較兩棵虛擬DOM樹的不同
  2. const patches = diff(tree, newTree);
  3. // 5. 在真正的DOM元素上應用變更
  4. patch(root, patches);

結果如圖

相關代碼可以查看patch.js

參考

深度剖析:如何實現一個 Virtual DOM 算法

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/106487.html

相關文章

  • React && VUE Virtual Dom的Diff算法統一之路 snabbd

    摘要:毫無疑問的是算法的復雜度與效率是決定能夠帶來性能提升效果的關鍵因素。速度略有損失,但可讀性大大提高。因此目前的主流算法趨向一致,在主要思路上,與的方式基本相同。在里面實現了的算法與支持。是唯一添加的方法所以只發生在中。 VirtualDOM是react在組件化開發場景下,針對DOM重排重繪性能瓶頸作出的重要優化方案,而他最具價值的核心功能是如何識別并保存新舊節點數據結構之間差異的方法,...

    shixinzhang 評論0 收藏0
  • 深入React知識點整理(一)

    摘要:以我自己的理解,函數式編程就是以函數為中心,將大段過程拆成一個個函數,組合嵌套使用。越來越多的跡象表明,函數式編程已經不再是學術界的最愛,開始大踏步地在業界投入實用。也許繼面向對象編程之后,函數式編程會成為下一個編程的主流范式。 使用React也滿一年了,從剛剛會使用到逐漸探究其底層實現,以便學習幾招奇技淫巧從而在自己的代碼中使用,寫出高效的代碼。下面整理一些知識點,算是React看書...

    Gilbertat 評論0 收藏0
  • React系列 --- 簡單模擬語法(一)

    摘要:系列系列簡單模擬語法一系列合成事件與二系列算法實現分析三系列從到再到四系列與部分源碼解析五系列從使用了解的各種使用方案六前言我們先不講什么語法原理先根據效果強行模擬語法使用實現一個簡易版的第一步我們先用類 React系列 React系列 --- 簡單模擬語法(一)React系列 --- Jsx, 合成事件與Refs(二)React系列 --- virtualdom diff算法實現分析...

    piglei 評論0 收藏0
  • 虛擬DOM與DIFF算法學習

    摘要:比較虛擬與的差異,以及對節點的操作,其實就是樹的差異比較,就是對樹的節點進行替換。忽略掉這種特殊的情況后,大膽的修改了算法按直系兄弟節點比較比較。這當中對比的細節才是整個算法最精粹的地方。 一、舊社會的頁面渲染 ???????在jQuery橫行的時代,FEer們,通過各種的方式去對頁面的DOM進行操作,計算大小,變化,來讓頁面生動活潑起來,豐富的DOM操作,讓一個表面簡單的頁面能展示出...

    codergarden 評論0 收藏0
  • React系列 --- Jsx, 合成事件與Refs(二)

    摘要:系列系列簡單模擬語法一系列合成事件與二系列算法實現分析三系列從到再到四系列與部分源碼解析五系列從使用了解的各種使用方案六的誕生他是的一種擴展語法。這個函數接受組件的實例或元素作為參數,以存儲它們并使它們能被其他地方訪問。 React系列 React系列 --- 簡單模擬語法(一)React系列 --- Jsx, 合成事件與Refs(二)React系列 --- virtualdom di...

    LiuZh 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<