本内容を利用した場合の一切の責任を私は負いません。
ソートは内部関数だから速そうと思って使ってたけど、reduceは対象値以外の処理を捨てるなら速そう。
で、計ってみた。
考えてみればreduceの処理量はO(n)だか。
ソートは内部アルゴリズムにもよるけど、少なくともこれよりは多いはず。
ま、それを内部でするかスクリプトでするかが一番大事なとこなんだけど(笑)
なにげにreduceは元の配列を変更しないのも良いとこ。
バージョン
- OS
OS 名: Microsoft Windows 10 Home
OS バージョン: 10.0.19045 N/A ビルド 19045
システムの種類: x64-based PC - node.js
node-v20.9.0-win-x64.zip
#ソース
a.js
function aa() {
let total;
// console.time("elap3");
total = 0;
for (let indexA = 0; indexA < 10; indexA++) {
for (let index = 0; index < 1000 * 1000; index++) {
let c = index & 0xff;
total += c & 1;
}
}
// console.timeEnd("elap3")
// console.log(total);
return;
}
const SIZE = 1000;
var datas = [];
for (let index = 0; index < SIZE; index++) {
datas.push(
{
"value": Math.random()
}
);
}
for (const data of datas) {
// console.log(data["value"]);
}
console.time("elap1");
var resultReduce = datas.reduce(
(cur, acc) => {
aa();
if (cur["value"] > acc["value"]) {
acc = cur;
}
return acc;
},
0
);
console.timeEnd("elap1")
console.log(resultReduce["value"]);
for (let index = 0; index < 10; index++) {
// console.log(datas[index]["value"]);
}
console.time("elap2");
datas.sort(
(a, b) => {
aa();
return b["value"] - a["value"];
}
);
console.timeEnd("elap2")
console.log(datas[0]["value"]);
for (let index = 0; index < 10; index++) {
// console.log(datas[index]["value"]);
}
出力
node.js
elap1: 5979.81005859375 ms
elap1: 5.980s
0.9993377285469689
elap2: 52072.816162109375 ms
elap2: 52.073s
0.9993377285469689