[英]Fast array chunking in Node.js
我正在對長數據集使用數組分塊。 我需要創建一個新的一定大小的塊數組。 當前,我使用此解決方案,但它顯示出不良的性能。
function array_to_chunks(data, size){
let chunks = []
let d = data.slice()
while (d.length >= size) chunks.push(d.splice(0, size))
return chunks
}
我想找到一個更好的主意,即如何足夠快地執行它以及為什么我的代碼不能很好地執行。
由於您不必復制數組,因此它的性能略高:
const createGroupedArray = function (arr, chunkSize) {
if (!Number.isInteger(chunkSize)) {
throw 'Chunk size must be an integer.';
}
if (chunkSize < 1) {
throw 'Chunk size must be greater than 0.';
}
const groups = [];
let i = 0;
while (i < arr.length) {
groups.push(arr.slice(i, i += chunkSize));
}
return groups;
};
如果您正在執行I / O,請使用Node.js流:
const strm = new Writable({
write(chunk, enc, cb){
// do whatever
}
});
我很想聽聽您對這種方法的看法:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] const size = 5 const chunkIt = (arr, size) => { let buckets = [] // Just create the buckets/chunks storage for (let i = 1; i <= Math.ceil(arr.length / size); i++) { buckets.push([]) } // Put in the buckets/storage by index access only for (let i = 0; i < arr.length; i++) { var arrIndex = Math.ceil((i + 1) / size) - 1 buckets[arrIndex].push(arr[i]) } return buckets; } console.log(chunkIt(arr, size))
我做了一些基本的JS基准測試,效果很好。 這個想法是要預先創建存儲桶,因為該操作不應該那么昂貴,然后只需按索引即可。
您可以使用lodash 塊方法,這可以滿足您的需求
const _ = require('lodash');
_.chunk([1,2,3,4,5,6],2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.