Fastest Way to get a uniquely index item from the property of an array

前端 未结 2 1040
终归单人心
终归单人心 2020-11-30 14:36

Make an array like this which represents what I\'m looking for:

$array = @(1..50000).foreach{[PSCustomObject]@{Index=$PSItem;Property1=\'Hello!\';Property2=(         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 15:03

    The fastest way I think is to use a Hashtable and take it for granted that building this would take some time. Also, I would reverse the Hashtable, so that the property you want to seek is the key and the array indexd will be the value.

    Note that while your example creates an array with start index 1, you need to account for that when retrieving the exact index (starting at 0) later. Also note that by using (Get-Random) for the property to search for leaves you with possible duplicate values. For demo this is fine, but remember that while doing so, the index found will be the last index in the series of duplicates..

    # create the demo array of objects
    $startIndex = 0
    $array = @($startIndex..50000).Foreach{[PSCustomObject]@{Index=$PSItem; Property1='Hello!'; Property2=(Get-Random)}}
    
    # create the hashtable where Property2 is the key and the array index the value
    Write-Host 'Create HashTable: ' -NoNewline
    (Measure-Command { $ht = @{}; foreach ($i in $array) { $ht[$i.Property2] = ($i.Index - $startIndex) } }).TotalMilliseconds
    
    # try and find the index. This will take longer if there was no Property2 with value 43122 
    Write-Host 'Find array index: ' -NoNewline
    (Measure-Command { $ht[43122] }).TotalMilliseconds
    

    Output on my Windows 7 machine (12 GB RAM, SSD disk):

    Create HashTable: 250.3011
    Find array index: 0.3865
    

提交回复
热议问题