In the previous post I provided a quick introduction to creating and using a hashtable object. If you are paying attention, you might have asked “Why would I go to extra work to create a hashtable when I can make the original object work?” The answer is performance…but lets expand on this answer.
We can use Measure-Command to show how long each of these statements takes to execute. Here is a quick refresher on using Measure-Command to show how long it takes to execute a command…just replace “PUT EACH COMMAND HERE” with your actual command:
[cc lang=”Powershell”]
(Measure-Command { “PUT EACH COMMAND HERE” }).TotalMilliseconds
[/cc]
Using the examples from the previous post, we return Total Millisecond execution times of:
Example | Execution Time (ms) |
2: Select item from array object | 19.0030 |
3: Create a hashtable from array object | 19.2045 |
4: Select item from hashtable | 0.0311 |
In this sample, returning a value from the hashtable (example 4) is 600 times faster than using the array object (example 2)! Just because this step was faster, it doesn’t mean hashtables are always best. If we take into account the overhead from creating the hashtable (add the execution times of example 3 and 4 together), then using the array object is actually more efficient. The performance gain is only noticeable if you plan to re-use the hashtable over several iterations.
[cc lang=”Powershell”]
# Example 5: Selecting multiple times from array object
(Measure-Command {
($colorCodes | Where-Object {$_.ColorName -eq ‘Red’}).Code
($colorCodes | Where-Object {$_.ColorName -eq ‘Blue’}).Code
($colorCodes | Where-Object {$_.ColorName -eq ‘Green’}).Code
($colorCodes | Where-Object {$_.ColorName -eq ‘Black’}).Code
}).TotalMilliseconds
# Example 6: Creating hashtable and selecting from it multiple times
(Measure-Command {
$colorCodeHT = @{}
$colorCodes | %{ $colorCodeHT.Add($_.ColorName, $_.Code) }
$colorCodeHT[‘Red’]
$colorCodeHT[‘Blue’]
$colorCodeHT[‘Green’]
$colorCodeHT[‘Black’]
}).TotalMilliseconds
[/cc]
Example | Execution Time (ms) |
5: Select from array object multiple times | 57.7053 |
6: Create hashtable and select from it multiple times | 17.8322 |
Even though a hashtable requires a bit of setup, it becomes more efficient with repetitive use. The example with HTML color codes only has around 290 items in the hashtable. This performance improvement is more noticeable with larger hashtables, especially when they are used many times within the script.