javascript 数値の通貨変換で「Intl.NumberFormat」と「toLocaleString」とのパフォーマンスを計測する
- 作成日 2022.09.08
- javascript
- javascript

javascriptで、「Intl.NumberFormat」と「toLocaleString」で数値の通貨変換処理を行った時のパフォーマンスを計測するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.101
数値の通貨変換
「performance.now」を使用して、「Intl.NumberFormat」と「toLocaleString」を使用して、
数値の通貨変換を行う処理を1万回実行し、パフォーマンスを計測するサンプルコードとなります。
<script>
// 実行回数
const times = 10_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 num = 123456789;
let result;
// 計測
start = performance.now();
for (let i = 0; i < times; ++i) {
result = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' } ).format(num)
}
end = performance.now();
benchmark('Intl.NumberFormat', start, end);
// 計測
start = performance.now();
for (let i = 0; i < times; ++i) {
result = (num).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
end = performance.now();
benchmark('toLocaleString', start, end);
</script>
実行結果(chrome 104.0.5112.101)
<1回目>
実行回数:10000回 関数名:Intl.NumberFormat 実行時間:348(ms)
実行回数:10000回 関数名:toLocaleString 実行時間:291(ms)
<2回目>
実行回数:10000回 関数名:Intl.NumberFormat 実行時間:418(ms)
実行回数:10000回 関数名:toLocaleString 実行時間:288(ms)
<3回目>
実行回数:10000回 関数名:Intl.NumberFormat 実行時間:317(ms)
実行回数:10000回 関数名:toLocaleString 実行時間:290(ms)
「toLocaleString」を使用した方が、速いという結果になりました。
firefox101でも、同じ結果になりました。
<1回目>
実行回数:10000回 関数名:Intl.NumberFormat 実行時間:435(ms)
実行回数:10000回 関数名:toLocaleString 実行時間:376(ms)
<2回目>
実行回数:10000回 関数名:Intl.NumberFormat 実行時間:424(ms)
実行回数:10000回 関数名:toLocaleString 実行時間:384(ms)
<3回目>
実行回数:10000回 関数名:Intl.NumberFormat 実行時間:408(ms)
実行回数:10000回 関数名:toLocaleString 実行時間:383(ms)
-
前の記事
mac ログアウトのダイヤログを開くショートカットキー 2022.09.08
-
次の記事
Redis 一度に複数keyの値を取得する 2022.09.08
コメントを書く