javascript - 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
}
});
推荐阅读
- postgresql - PostgreSQL - 仅选择前一个条目满足条件的行
- java - 在 JavaFX 中二次调整网格窗格的大小
- eclipse - GDB 7.5 兼容的 eclipse CDT 版本是什么
- jasper-reports - 将外部参数传递给 XML 文件数据适配器时出现问题
- android - 当我尝试在 Android Studio 中使用 gradle 从私有 Nexus 存储库中获取 .jar 库文件时,为什么会出现错误“无法解决依赖关系”?
- reactjs - 状态与 Redux。react-router如何实现页面加载和预取数据加载?
- kubernetes - 如何启动 kubelet 服务?
- reactjs - 我无法使用画布作为子组件绘制矩形
- c# - C# ASP.NET,在异步调用堆栈中设置 Thread.CurrentPrincipal?
- yocto - 在 Yocto 配方中设置新的用户权限