PowerShell is slow to convert integers to strings


I am writing a PowerShell script where many integers have to be converted to strings. I am using the ToString method to do this, as in:

Unfortunately, this seems to be very slow (I omitted the execution policy warning):

I am using PowerShell 2 and Python 3.

This is the contents of int_to_str.ps1:

This is the contents of int_to_str.py:

As you can see, both scripts convert integers from 1 to 1,000,000 to strings. However, while PowerShell takes 6.75 seconds, Python only takes 0.37 seconds, making Python 18 times faster. In the actual PowerShell script that I am writing, it takes about three hours to convert all of the integers to strings, so an 18-fold speed improvement would be welcome.

Is there a faster way to convert an int to a string in PowerShell 2?


To answer your question, even in .NET (which is what you’re using with PowerShell), here is a great article on the int->string conversion you care about: http://cc.davelozinski.com/c-sharp/fastest-way-to-convert-an-int-to-string.

As far as byte array conversions from AD, here is a test I did and with explicit casting to a [string[]], I nearly always saw gains over using .tostring(). The gains ranged from 50% to equivalent but it was consistently faster:


PowerShell is slow to convert integers to strings by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply