Search

my categories

Blogroll

Fast New PSCustomObject.

June 15th, 2008 by Karl

Given the context on the last few posts. I’ve made a simple helper method in C# that can take a simple powershell hashtable and create a PSCustomObject based on it. Here is an example of how you can call it.

[snapinini.newobjecthelper]::newObjectFast(@{name="karl";age=31;now = [datetime]::Now})

very simple and its at least 6 times faster than the closest other technique in powershell. Most of hte overhead is in creating the hashtable. (otherwise its 90 times faster). The hashtable syntax is very convenient however maybe even its overhead is too much and we deserve a better way.

Here is the C# method. Its pretty basic stuff.

 

public static PSObject newObjectFast( Hashtable noteproperties )
        {
            PSObject obj = new PSObject();
            if (noteproperties != null)            
                foreach(DictionaryEntry item in noteproperties)
                    obj.Properties.Add(new PSNoteProperty((string)item.Key,item.Value));            
            return obj;
        }

- Karl

Posted in Bare Metal, Gotchas, Nuances and Facets, Powershell, performance |

3 Responses

  1. The PowerShell Guy : PowerShell Performance Series Part 2 (.NET method call not always faster as PowerShell shortcut) Says:

    […] Fast New PSCustomObject. […]

  2. Hal Rottenberg Says:

    Karl,

    Can you explain this part in more detail? “its at least 6 times faster than the closest other technique in powershell”?

    What are you comparing it to, what times did you see?

  3. Karl Says:

    Hal, 6 times faster than select-object method, or about 30 times faster than using add-member

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.