首页 > 解决方案 > 为什么 Import-Csv 的 Sort-Object 对于 100 万条记录很慢

问题描述

我需要对 csv 文件的第一列(列可能不同)进行排序。由于我的 csv 文件有超过一百万条记录,因此执行以下命令需要 10 分钟。

有没有其他方法可以优化代码以加快执行速度?

$CsvFile = "D:\Performance\10_lakh_records.csv"
$OutputFile ="D:\Performance\output.csv"

    Import-Csv $CsvFile  | Sort-Object { $_.psobject.Properties.Value[1] } | Export-Csv -Encoding default -Path $OutputFile -NoTypeInformation

标签: powershell

解决方案


您可以尝试使用[array]::Sort()可能证明比 更快的静态方法Sort-Object,尽管它确实需要一个额外的步骤来首先获取所有值的一维数组以进行排序..

尝试

$CsvFile    = "D:\Performance\10_lakh_records.csv"
$OutputFile = "D:\Performance\output.csv"

# import the data
$data = Import-Csv -Path $CsvFile

# determine the column name to sort on. In this demo the first column
# of course, if you know the column name you don't need that and can simply use the name as-is
$column = $data[0].PSObject.Properties.Name[0]

# use the Sort(Array, Array) overload method to sort the data by the 
# values of the column you have chosen.
# see https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-5.0#System_Array_Sort_System_Array_System_Array_
[array]::Sort($data.$column, $data)

$data | Export-Csv -Encoding default -Path $OutputFile -NoTypeInformation

推荐阅读