在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

使用上述演示数据,运行时间为122429499秒。因为我必须非常频繁地运行这种任务,而且实际数据有时甚至更大,并且最多有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

上述演示输入的运行时间现在是03300486秒。

最新更新