PowerShell Performance Tip – Use JavaScriptSerializer instead of ConvertTo-Json

While working on a bulk API function that sends a lot of  JSON data to elasticsearch, I noticed that using the native .NET Framework object System.Web.Script.Serialization.JavaScriptSerializer yields huge performance gains versus using the ConvertTo-Json cmdlet.

Here’s a quick test that compares both methods:

Add-Type -AssemblyName System.Web.Extensions
$jsonSerializer=New-Object -TypeName System.Web.Script.Serialization.JavaScriptSerializer
measure-command{for($i=0;$i -lt 10000;$i++){$null=$jsonSerializer.Serialize("test");}}

Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 127
Ticks : 1272587
TotalDays : 1.47290162037037E-06
TotalHours : 3.53496388888889E-05
TotalMinutes : 0.00212097833333333
TotalSeconds : 0.1272587
TotalMilliseconds : 127.2587

measure-command {for($i=0;$i -lt 10000;$i++){$null="test"| ConvertTo-Json;}}

Days : 0
Hours : 0
Minutes : 0
Seconds : 3
Milliseconds : 874
Ticks : 38746129
TotalDays : 4.4845056712963E-05
TotalHours : 0.00107628136111111
TotalMinutes : 0.0645768816666667
TotalSeconds : 3.8746129
TotalMilliseconds : 3874.6129

As you can see, the performance gain is rather significant! When you need to send millions of JSON object to a web service, that makes quite a difference.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s