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
So now we have the wmi object in the variable $wmics. So how do we get the name. Well here there are a few ways all giving the same answer.
$wmics.name
$wmics|Select-Object -ExpandProperty name
$wmics.GetPropertyValue('Name')
All of those return the same information, Well if you dont really believe they are really the same lets get the type of all returned objects.

$wmics.name.gettype()
($wmics|Select-Object -ExpandProperty name).gettype()
$wmics.GetPropertyValue('Name').GetType()
Everyone of them return the following:
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
This gives:

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.