Hero Image
LocalStorage vs. IndexedDB vs. Cookies vs. OPFS vs. WASM-SQLite

LocalStorage vs. IndexedDB vs. Cookies vs. OPFS vs. WASM-SQLite 現代瀏覽器可用的 Storage API Cookies Cookies 會儲存小型的鍵值資料,主要用於工作階段管理、個人化與追蹤。Cookies 可以設定多種安全選項,例如存活時間或網域屬性,以便在多個子網域之間共用。 LocalStorage LocalStorage 只適合儲存少量且需要跨 session 保存的資料,並且受限於 5MB 的容量上限。要儲存複雜資料,通常需要轉成字串,例如使用 JSON.stringify()。這個 API 不是非同步的,代表在操作時會阻塞你的 JavaScript 程序,因此執行重型操作可能會讓 UI 無法渲染。 IndexedDB IndexedDB 是一個用於儲存大量結構化 JSON 資料的低階 API。雖然使用起來有些困難,但 IndexedDB 可以利用索引並支援非同步操作。它缺乏複雜查詢能力,只能迭代索引,更像是其他函式庫的底層基礎,而非完整的資料庫。 儲存容量限制 技術 上限 Cookie 4 KB LocalStorage 每個來源 4 MB 到 10 MB IndexedDB 取決於瀏覽器實作 OPFS 取決於可用的磁碟空間 效能比較 初始化時間 技術 時間(毫秒) IndexedDB 46 OPFS 主執行緒 23 OPFS WebWorker 26.8 WASM SQLite(記憶體) 504 WASM SQLite(IndexedDB) 535 小型寫入延遲 技術 時間(毫秒) Cookies 0.058 LocalStorage 0.017 IndexedDB 0.17 OPFS 主執行緒 1.46 OPFS WebWorker 1.54 WASM SQLite(記憶體) 0.17 WASM SQLite(IndexedDB) 3.17 小型讀取延遲 技術 時間(毫秒) Cookies 0.132 LocalStorage 0.0052 IndexedDB 0.1 OPFS 主執行緒 1.28 OPFS WebWorker 1.41 WASM SQLite(記憶體) 0.45 WASM SQLite(IndexedDB) 2.93

Hero Image
進階 Shell 腳本技巧:用 Bash 自動化複雜任務

進階 Shell 腳本技巧:用 Bash 自動化複雜任務 使用內建指令 內建指令執行更快,因為不需要載入外部程序。 減少子殼層 子殼層會帶來效能成本。 # Inefficient output=$(cat file.txt) # Efficient output=$(<file.txt) 使用陣列處理大量資料 處理大量資料時,陣列比多個變數更有效率,也更好管理。 # Inefficient item1="apple" item2="banana" item3="cherry" # Efficient items=("apple" "banana" "cherry") for item in "${items[@]}"; do echo "$item" done 啟用 Noclobber 避免檔案被意外覆寫。 set -o noclobber 使用函式 函式可以封裝並重用程式碼,讓腳本更乾淨、重複更少。 高效的檔案操作 進行檔案操作時,使用更有效率的技巧以降低資源消耗。 # Inefficient while read -r line; do echo "$line" done < file.txt # Efficient while IFS= read -r line; do echo "$line" done < file.txt 平行處理 像 xargs 和 GNU parallel 這類工具非常實用。 錯誤處理 健全的錯誤處理對建立可靠、易維護的腳本至關重要。 # Exit on Error: Using set -e ensures that your script exits immediately if any command fails, preventing cascading errors. set -e # Custom Error Messages: Implement custom error messages to provide more context when something goes wrong. command1 || { echo "command1 failed"; exit 1; } # Trap Signals: Use the `trap` command to catch and handle signals and errors gracefully. trap 'echo "Error occurred"; cleanup; exit 1' ERR function cleanup() { # Cleanup code } # Validate Inputs: Always validate user inputs and script arguments to prevent unexpected behavior. if [[ -z "$1" ]]; then echo "Usage: $0 <argument>" exit 1 fi # Logging: Implement logging to keep track of script execution and diagnose issues. logfile="script.log" exec > >(tee -i $logfile) exec 2>&1 echo "Script started" 自動化複雜的系統管理工作 自動化備份 系統監控 使用者管理 自動更新 網路設定