arrays - 需要在 Powershell 中以更快的方式将大型数组合并到单个二维数组中
问题描述
我正面临一种情况,我需要一种非常快速的方法来通过 Powershell 合并多个大型数组。最初数据来自 json 输入,但为了解释我的挑战,这里有一个小代码片段,它会产生类似的情况:
$columnCount = 10 # this number is NOT fixed!
$rowCount = 10KB
$allData = @()
$titles = @()
# create sample input data for the scenario that I need to solve:
foreach($i in 1..$columnCount) {
$titles += "Column$i"
$columnData = ,"$i" * $rowCount
$alldata += ,$columnData
}
现在我需要一种快速的方法来将这 10 个一维数组及其每列的数据合并到一个具有正确列标题的单个二维数组中。
我从这段代码开始:
$t = [System.Diagnostics.Stopwatch]::StartNew()
$result = [System.Collections.ArrayList]::new()
$columnMaxId = $columnCount-1
$rowMaxId = $allData[0].count-1
foreach($row in 0..$rowMaxId) {
$line = [PsObject]::new()
foreach($column in 0..$columnMaxId) {
$line | Add-Member -MemberType NoteProperty -Name $titles[$column] -Value $allData[$column][$row]
}
$null = $result.Add($line)
}
$t.Stop()
$t.Elapsed.TotalSeconds
上述演示数据的运行时间为 12,2429499 秒。因为我必须非常频繁地运行这种任务,而且实际数据有时甚至更大并且有多达 30 列,所以这个解决方案不够快。我怎样才能加快速度?
解决方案
我最终使用数据表来完成上述任务。在数据表中添加行允许每行传递一个值数组,这样我就可以处理每行的动态长度。这是我的代码:
$t = [System.Diagnostics.Stopwatch]::StartNew()
$table = [System.Data.Datatable]::new()
foreach($title in $titles) {[void]$table.Columns.Add($title)}
$columnMaxId = $columnCount-1
foreach($row in 0..($rowCount-1)){
$dataRow = [System.Collections.ArrayList]::new()
foreach($column in 0..$columnMaxId){
[void]$dataRow.Add($allData[$column][$row])
}
[void]$table.Rows.Add([array]$dataRow)
}
$t.Stop()
$t.Elapsed.TotalSeconds
上述演示输入的运行时间现在为 0,3300486 秒。
推荐阅读
- karate - 具有默认值的嵌入式表达式 (JSON/YML)
- python - 如何使用numpy根据向量索引条件获取布尔二维数组?
- kubernetes - aws ebs csi 驱动程序无法使用附加到 ec2-instance 的 IAM 角色创建持久卷
- security - 我如何才能完全信任 SAML IDP?
- php - PHP CS Fixer - 丑陋的缩进
- python-3.x - 无法根据条件获取索引
- r - 将脚注文本添加到各个医院的 ggplot2 图表
- python-3.x - Django:如何在不删除数据库的情况下将 cat_id 更改为 cat_slug?
- javascript - 我的 index.js 文件缺少 app.js 文件的哪一部分?
- c# - C# - 将列表 System.Object[] 转换为列表 System.Int32[]