powershell - 为什么 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
解决方案
您可以尝试使用[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
推荐阅读
- ios - 根据 Swift 中的属性删除数组对象
- python - 如何修复 Python Selenium CSV 文件循环问题?
- ios - 如何从图像选择器中获取 NSData?
- java - 用句子中的符号将每个单词的第一个字母大写
- javascript - 滚动页面而不是反应中的div元素
- python - 如何在 Pytorch 中使用 for 循环长度作为优化参数
- python - 如何在python中将数字转换为整数
- typescript - 点击后如何关闭sidenav?
- java - 对于 angelikalanger 上的泛型类中的静态成员,“每个封闭类型中的每个静态成员都存在一次”是什么意思
- sql-server - 使用 Pyspark 将 SQL 查询从 DataBricks 发送到 SQL Server