ローカルストレージへのデータ保存時間を計測してみた

PCスペック

ローカルストレージとは

ローカルストレージとは、Web Storage APIの一部としてブラウザに組み込まれている機能で、データをキーと値のペアとしてブラウザに保存できます。

ウェブストレージ API - Web API | MDN

ローカルストレージへの保存は同期的

Both sessionStorage and localStorage in Web Storage are synchronous in nature. This means that when data is set, retrieved, or removed from these storage mechanisms, the operations are performed synchronously, blocking the execution of other JavaScript code until the operation is completed. This synchronous behavior can potentially affect the performance of the web application, especially if there is a large amount of data being stored or retrieved.

Web Storage API - Web APIs | MDN

とあるので、実際に大量のデータをローカルストレージに保存した場合に、どのくらいの時間がかかるのか計測してみました。

ローカルストレージの容量を調べる

Browsers can store up to 5 MiB of local storage, and 5 MiB of session storage per origin.

Storage quotas and eviction criteria - Web APIs | MDN

とは書いてありますが、実際にどのくらいのサイズまで保存できるのか試してみます。 いつも使っているReactで書いてみました。

    const testStorageLimit = () => {
        const testString = 'a'.repeat(1024); // 1KBのテストデータ
        let i = 0;
        setStartTime(performance.now());

        const intervalId = setInterval(() => {
            try {
                localStorage.setItem(`testKey${i}`, testString);
                i++;
            } catch (e) {
                clearInterval(intervalId); // ループを終了
                if (e.name === 'QuotaExceededError') {
                    setEndTime(performance.now());
                    setStatus(`限界に達しました: ${i} KB`);
                    localStorage.clear();
                }
            }
        }, 0);
    };
    return (
        <>
            <div>
                <button onClick={testStorageLimit}>ストレージ限界テスト開始</button>
                <div>ステータス: {status}</div>
                {endTime > 0 && (
                    <div>所要時間: {(endTime - startTime).toFixed(2)} ミリ秒</div>
                )}
            </div>

ボタンをクリックすると、1KBのデータを繰り返し保存し、 ローカルストレージがいっぱいになるとテストが停止し、結果と所要時間が表示されるようにしました。


やはり5MiB程度のようです。

容量ごとの所要時間を調べる

容量の限界値が分かったので、次は 1K,10K,100K,1M,5Mサイズのデータを保存してみます。

const testDataSizes = [1, 10, 100, 1000, 5000]; // KBで指定

    const performTest = async () => {
    const newResults = [];

    for (const size of testDataSizes) {
        const data = new Array(size * 1024).fill('a').join('');
        const key = `testData-${size}KB`;
        const startTime = performance.now();
         try {
            localStorage.setItem(key, data);
            const endTime = performance.now();
            const timeTaken = (endTime - startTime).toFixed(2);
            newResults.push(`${size}KB: ${timeTaken} ms`);
        } catch (e) {
            newResults.push(`${size}KB: Error storing data`);
        }

        localStorage.removeItem(key);
    }

     <div>
        <button onClick={performTest}>パフォーマンステスト開始</button>
        <ul>
            {results.map((result, index) => (
                <li key={index}>{result}</li>
           ))}
        </ul>
     </div>
}

結果

3回計測して平均を出してみました。   

Size (KB) Trial 1 (ms) Trial 2 (ms) Trial 3 (ms) Average (ms)
1 0.1 0.1 0.1 0.1
10 0.1 0.2 0.1 0.133333
100 0.7 0.8 0.2 0.566667
1000 4.2 4.3 3.4 3.96667
5000 23.6 32.7 19.3 25.2

予想よりかなり高速でした。

ソースコード

sandbox/localstorage_test/src/App.jsx at main · kei-kmj/sandbox · GitHub