Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance 为什么powershell验证大字节[]数组的速度如此之慢?_Performance_Powershell_Parameter Passing - Fatal编程技术网

Performance 为什么powershell验证大字节[]数组的速度如此之慢?

Performance 为什么powershell验证大字节[]数组的速度如此之慢?,performance,powershell,parameter-passing,Performance,Powershell,Parameter Passing,我花了一些时间试图在powershell应用程序中找到一个瓶颈,但从未怀疑这只是一个缓慢的参数验证。示例代码说明了该问题: 功能测试验证性能 { param( [ValidateNotNullOrEmpty()] [字节[]] $Data ) $sw.Stop() 写入主机“在$([Math]::Round($sw.appeased.total毫秒))ms之后执行” } 性能测试 { param( [字节[]] $Data ) $sw.Stop() 写入主机“在$([Math]::Round($

我花了一些时间试图在powershell应用程序中找到一个瓶颈,但从未怀疑这只是一个缓慢的参数验证。示例代码说明了该问题:

功能测试验证性能
{
param(
[ValidateNotNullOrEmpty()]
[字节[]]
$Data
)
$sw.Stop()
写入主机“在$([Math]::Round($sw.appeased.total毫秒))ms之后执行”
}
性能测试
{
param(
[字节[]]
$Data
)
$sw.Stop()
写入主机“在$([Math]::Round($sw.appeased.total毫秒))ms之后执行”
}
$buf=[IO.File]::ReadAllBytes('C:\17MB_File.bin'))
写入主机“通过验证调用…”
$sw=[Diagnostics.Stopwatch]::StartNew()
测试验证性能$buf
写入主机“`n无验证调用…”
$sw=[Diagnostics.Stopwatch]::StartNew()
测试Novalidate性能$buf
输出:

Calling with validation...
Executing after 1981ms

Calling without validation...
Executing after 3ms
我的问题是:为什么
[ValidateNotNullOrEmpty()]
的速度如此之慢,以至于(正如其名称所述)它只检查null或空参数?

当您向集合添加(大多数)验证属性时,它将应用于集合中的每个项;而不是整个集合,因此验证将针对每个单独的字节运行

长大了

测试它是否为空的最简单方法就是将参数设置为强制参数;那么将不接受空数组:

function Test-ValidatePerformance
{
    param(
        [Parameter(Mandatory)]
        [Byte[]]
        $Data
    )

    $sw.Stop()

    Write-Host "Executing after $([Math]::Round($sw.Elapsed.TotalMilliSeconds))ms"
}
注意:如原始海报所示,并已确认

如果希望参数是可选的,但如果提供了参数,则该参数不能为空,则可以使用
[ValidateCount()]
,这应该很快:

function Test-ValidatePerformance
{
    param(
        [ValidateCount(1,[int]::MaxValue)]
        [Byte[]]
        $Data
    )

    $sw.Stop()

    Write-Host "Executing after $([Math]::Round($sw.Elapsed.TotalMilliSeconds))ms"
}
或者您可以只执行签入代码,而不使用验证属性

function Test-ValidatePerformance
{
    param(
        [Byte[]]
        $Data
    )

    if (-not $Data -and $PSBoundParameters.ContainsKey('Data')) {
        throw [System.ArgumentException]'An empty array is not allowed'
    }

    $sw.Stop()

    Write-Host "Executing after $([Math]::Round($sw.Elapsed.TotalMilliSeconds))ms"
}

设置为强制会导致速度变慢(2385ms),但
ValidateCount()
。现在我更感兴趣了。@karliwson嗯,这很有趣。。。我也是intrigued@briantist:真有趣。让我想起了@karliwson,这是一个在PowerShell core中解决的bug。供参考:谢谢你们两位;我在答案中把这些问题联系起来了。