Virtualized List 隨手記

James Pan
Nov 30, 2022

--

試著幫瀏覽器減輕些負擔吧!

Photo by Eneko Uruñuela

身為前端工程師, 應該多少都會遇到要將大量資料呈現在畫面。

但你知道嗎?如果現在有一百、一千或是更多筆資料需要渲染,可能就會是壓垮效能的兇手之一。因為過多不必要的資訊或是 DOM 被建立,而我們不能確保所有呈現出來的東西都是使用者需要知道或是使用者一定會看到的,進而造成效能浪費。

於是來介紹今天的主角 Virtualized List。

因對於 React 較為熟悉,因此本篇會圍繞 react-window 做說明

它解決了什麼問題?

一般在學習新技術或是工具時我都會這樣問自己。

If your application renders long lists of data (hundreds or thousands of rows), we recommend using a technique known as “windowing”. This technique only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created.

以上引用自 React 官方的說明,簡單說,當有大量的資料需要渲染,建議使用名為 “windowing” 的技術,因為它一次只會渲染少數的資料在畫面上,必免大量的 DOM 被建立,藉此提高效能。

並且在官方文件裡也提到可使用 react-window 以及 react-virtualized 達到提升效能目的。基本上如果 react-window 符合開發需求即可優先使用,相較於後者,前者更輕量、高效能,但後者所提供的 feature 較為齊全。更細節的差異有興趣的人可以再自行研究。

那麼可能有人會問,大量的 DOM 被建立會帶來什麼影響。

  • 第一次載入耗時過久:瀏覽器等待資料載入後,才能將資料 painting 於畫面
  • 消耗更多 GPU Memory:不利於規格較差的設備,可能會造成卡頓

以下附上使用 react-window 前後的比對結果:

沒有使用 react-window
使用 react-window

可以看到畫面右側 DOM 節點以及左側追蹤 GPU 的小工具,在使用 react-window 後除了 DOM 節點減少以外,GPU Memory 的使用率也減少了約三倍。

瞭解了 react-window 帶來的好處之後也自己實作體驗這個工具所帶來的效益( Sample Code),有需要參考的話可以 pull 下來,如果有更好的使用建議也歡迎跟我說!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response