Node.js 中的快速数组分块

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
  }
});

你可以使用 lodash chunk 方法,这就是你需要的

const _ = require('lodash');
_.chunk([1,2,3,4,5,6],2);

我很想听听您对这种方法的看法:

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 基准测试,效果很好。这个想法是预先创建桶,因为该操作不应该那么昂贵,然后只需按索引推送。