Improve performance of update comparison in cache lookup

Replaces the `Compare-Object` cmdlet with a faster, manual loop comparison on pre-sorted arrays to optimize the VHDX cache check for matching updates.

This change also refactors the extraction of update filenames for better readability and adds checks for empty collections to improve script robustness.
This commit is contained in:
rbalsleyMSFT
2025-07-21 16:13:14 -07:00
parent ba1dd3df6b
commit c9499d839c
+17 -7
View File
@@ -4607,11 +4607,9 @@ try {
# Extract file names from URLs for comparison # Extract file names from URLs for comparison
$requiredUpdateFileNames = @() $requiredUpdateFileNames = @()
foreach ($update in $requiredUpdates) { if ($requiredUpdates.Count -gt 0) {
$fileName = ($update.Url -split '/')[-1] $requiredUpdateFileNames = @(($requiredUpdates.Url | ForEach-Object { ($_ -split '/')[-1] }) | Sort-Object)
$requiredUpdateFileNames += $fileName
} }
$requiredUpdateFileNames = $requiredUpdateFileNames | Sort-Object
foreach ($vhdxJson in $vhdxJsons) { foreach ($vhdxJson in $vhdxJsons) {
try { try {
@@ -4625,11 +4623,23 @@ try {
if ($vhdxCacheItem.OptionalFeatures -ne $OptionalFeatures) { WriteLog 'OptionalFeatures mismatch, continuing'; continue } if ($vhdxCacheItem.OptionalFeatures -ne $OptionalFeatures) { WriteLog 'OptionalFeatures mismatch, continuing'; continue }
$cachedUpdateNames = @() $cachedUpdateNames = @()
if ($vhdxCacheItem.IncludedUpdates) { if ($vhdxCacheItem.IncludedUpdates -and $vhdxCacheItem.IncludedUpdates.Count -gt 0) {
$cachedUpdateNames = $vhdxCacheItem.IncludedUpdates.Name | Sort-Object $cachedUpdateNames = @($vhdxCacheItem.IncludedUpdates.Name | Sort-Object)
} }
if ((Compare-Object -ReferenceObject $requiredUpdateFileNames -DifferenceObject $cachedUpdateNames).Length -gt 0) { # Manually compare the two sorted arrays of update names
$updatesMatch = $false
if ($requiredUpdateFileNames.Count -eq $cachedUpdateNames.Count) {
$updatesMatch = $true # Assume true and prove false
for ($i = 0; $i -lt $requiredUpdateFileNames.Count; $i++) {
if ($requiredUpdateFileNames[$i] -ne $cachedUpdateNames[$i]) {
$updatesMatch = $false
break
}
}
}
if (-not $updatesMatch) {
WriteLog 'IncludedUpdates mismatch, continuing' WriteLog 'IncludedUpdates mismatch, continuing'
continue continue
} }