javascript 数値にカンマをつける処理で「Intl.NumberFormat」と「toLocaleString」のパフォーマンスを計測する
- 作成日 2022.06.30
- 更新日 2023.01.24
- javascript
- javascript
javascriptで、「Intl.NumberFormat」と「toLocaleString」で同じ数値にカンマをつける処理を行った時のパフォーマンスを計測するサンプルコードを記述してます。ここでは「chrome」と「firefox」と「safari」の3つブラウザで結果を掲載してます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 109.0.5414.75
パフォーマンス計測
「performance.now」を使用して、「Intl.NumberFormat」と「toLocaleString」を使用して、
数値にカンマをつける処理を100万回実行し、パフォーマンスを計測するサンプルコードとなります。
<script>
// 実行回数
const times = 1_000_000;
// 空白を埋めるだけの関数
function spacePadding(val, n = 8) {
for (; val.length < n; val += ' ');
return val;
}
// 計測結果を表示
const benchmark = (name, start, end) => {
let report = (end - start).toPrecision(3);
// 表示を見やすくするため関数名に空白を埋める
name = spacePadding(name)
console.log(`実行回数:${times}回 関数名:${name} 実行時間:${report}(ms)`);
}
const In = new Intl.NumberFormat();
// 計測
start = performance.now();
for (let i = 0; i < times; ++i) {
In.format(123456)
}
end = performance.now();
benchmark('Intl.NumberFormat', start, end);
// 計測
start = performance.now();
for (let i = 0; i < times; ++i) {
(123456).toLocaleString()
}
end = performance.now();
benchmark('toLocaleString', start, end);
</script>
実行結果(chrome 109.0.5414.75)
<1回目>
実行回数:1000000回 関数名:Intl.NumberFormat 実行時間:431(ms)
実行回数:1000000回 関数名:toLocaleString 実行時間:402(ms)
<2回目>
実行回数:1000000回 関数名:Intl.NumberFormat 実行時間:430(ms)
実行回数:1000000回 関数名:toLocaleString 実行時間:423(ms)
<3回目>
実行回数:1000000回 関数名:Intl.NumberFormat 実行時間:449(ms)
実行回数:1000000回 関数名:toLocaleString 実行時間:435(ms)
ほぼ同じという結果になりました。
firefox109の場合も、同じような結果になりました。
<1回目>
実行回数:1000000回 関数名:Intl.NumberFormat 実行時間:599(ms)
実行回数:1000000回 関数名:toLocaleString 実行時間:617(ms)
<2回目>
実行回数:1000000回 関数名:Intl.NumberFormat 実行時間:545(ms)
実行回数:1000000回 関数名:toLocaleString 実行時間:578(ms)
<3回目>
実行回数:1000000回 関数名:Intl.NumberFormat 実行時間:507(ms)
実行回数:1000000回 関数名:toLocaleString 実行時間:540(ms)
safari15.5では「Intl.NumberFormat」のほうが速いという結果になりました。
実行回数:1000000回 関数名:Intl.NumberFormat 実行時間:882(ms)
実行回数:1000000回 関数名:toLocaleString 実行時間:4.10e+1(ms)
-
前の記事
SQL Server ID(IDENTITY)値を初期化する 2022.06.30
-
次の記事
mac Dockの表示・非表示を切り替えるショートカットキー 2022.06.30
コメントを書く