PowerShell v3 -使用[pscustomobject] 创建对象-更快! 12


PowerShell v2中,我们使用下面的方法创建自定义对象:

$CustomObject1 = New-Object psobject -Property @{a=1; b=2; c=3; d=4}
$CustomObject1 | Format-List

PowerShell v3中,我们可以使用[pscustomobject]来创建自定义对象:

$CustomObject2 = [pscustomobject]@{a=1; b=2; c=3
$CustomObject2 | Format-List

两中方法创建的都是具有NoteProperties属性的PSCustomObject对象,而不是hashtable对象:

$CustomObject1 | Get-Member
$CustomObject2 | Get-Member

那么,为什么我们要使用PSCustomObject呢?
首先,他使用你赋予的属性顺序,不作修改.
当然,更主要的理由是PSCustomObject更快!

有4中方法来创建自定义对象,我们来看看速度上的差异:

1) Select-Object

$TestSelect = {
(0..5000) | ForEach-Object {$CustomObject = "" | Select-Object Name,ID
$CustomObject.Name = "Test Name"
$CustomObject.ID = $_
$CustomObject
}
}
Measure-Command $TestSelect | Format-Table TotalSeconds -Autosize

2) Add-Member

$TestAddMember = {
(0..5000) | ForEach-Object {$CustomObject = New-Object psobject
$CustomObject | Add-Member -Name "Name" -Value "Test Name"
$CustomObject | Add-Member -Name "ID" -Value $_
$CustomObject
}
}
Measure-Command $TestAddMember | Format-Table TotalSeconds -Autosize

3) Property Parameter

$TestProperty = {
(0..5000) | ForEach-Object {New-Object psobject -Property @{Name = "Test Name"; ID = $_}}
}
Measure-Command $TestProperty | Format-Table TotalSeconds -Autosize

4) [pscustomobject]

$TestProperty = {
(0..5000) | ForEach-Object {[pscustomobject]@{Name = "Test Name"; ID = $_}}
}
Measure-Command $TestPSCustomObject | Format-Table TotalSeconds -Autosize

我们来总结下:

Select-Object = 7.74s

Add-Member = 28.87s

Property = 7.29

[pscustomobject] = 0.94s

 

原文连接:
powershell-v3-creating-objects-with-pscustomobject-its-fast

本文链接: https://www.pstips.net/creating-objects-with-pscustomobject-its-fast.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

12 条评论 “PowerShell v3 -使用[pscustomobject] 创建对象-更快!