A while ago I wrote a blogentry about different ways of obtaining the hostname. When I wrote that one I thought wonder how the different way of accessing the member values increases the cost. So this is a blogentry about that. There are different overheads depending on how you get your objects member. To illustrate this I have made a simple single WMI query and saved in a variable, from which we will now get the name of the computer.
First lets get the WMI object:
$wmics = Get-WMIObject -Class Win32_ComputerSystem
$wmics.name
$wmics|Select-Object -ExpandProperty name
$wmics.GetPropertyValue('Name')
$wmics.name.gettype()
($wmics|Select-Object -ExpandProperty name).gettype()
$wmics.GetPropertyValue('Name').GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
Benchmarking
So now we know that we get the same answer from all lets see how long time they take:
1..100000 | %{measure-command{$wmics.name}}|measure-object -Average Ticks
1..100000 | %{measure-command{$wmics|Select-Object -ExpandProperty name}}|measure-object -Average Ticks
1..100000 | %{measure-command{$wmics.GetPropertyValue('Name')}}|measure-object -Average Ticks
Method | Avg ticks |
---|---|
.Membername | 1040 |
Select -Expand | 1145 |
.GetPropertyValue() | 2946 |
So as we see some ways of obtaining member values can cost many more CPU cycles than others.