PowerShell 将整数转换为字符串的速度很慢

wec*_*sam 5 string int powershell performance type-conversion

我正在编写一个 PowerShell 脚本,其中许多整数必须转换为字符串。我正在使用该ToString方法来执行此操作,如下所示:

$i = 5
$i.ToString()
Run Code Online (Sandbox Code Playgroud)

不幸的是,这似乎很慢(我省略了执行策略警告):

PS I:\ADCC\Scripting Performance> .\int_to_str.ps1
6.747561
PS I:\ADCC\Scripting Performance> .\int_to_str.py
0.37243021680382793
Run Code Online (Sandbox Code Playgroud)

我正在使用 PowerShell 2 和 Python 3。

PS I:\ADCC\Scripting Performance> $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5485
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1


PS I:\ADCC\Scripting Performance> python --version
Python 3.6.1
Run Code Online (Sandbox Code Playgroud)

这是内容int_to_str.ps1

(Measure-Command {
    ForEach($i in 1..1000000){
        $i.ToString()
    }
}).TotalSeconds
Run Code Online (Sandbox Code Playgroud)

这是内容int_to_str.py

#!/usr/bin/env python3
import time
start = time.perf_counter()
for i in range(1, 1000000):
    str(i)
print(time.perf_counter() - start)
Run Code Online (Sandbox Code Playgroud)

如您所见,这两个脚本都将 1 到 1,000,000 之间的整数转换为字符串。然而,PowerShell 需要 6.75 秒,而 Python 只需要 0.37 秒,使 Python 快 18 倍。在我正在编写的实际 PowerShell 脚本中,将所有整数转换为字符串大约需要三个小时,因此速度提高 18 倍将是受欢迎的。

在 PowerShell 2 中是否有更快的方法将 an 转换int为 a string

wec*_*sam 6

我已经接受了@thepip3r 的回答,但我想从对以下两件事的评论中强调一些其他可能的解决方案:

  1. 您可以使用"$i"代替$i.ToString(). 它更快。
  2. 如果您使用的是 PowerShell 2,则可以尝试从 Microsoft 下载更新版本的 Windows 管理框架:https : //www.microsoft.com/en-us/download/details.aspx?id=50395

如果评论中出现更多解决方案,我将对其进行编辑。


the*_*p3r 5

要回答您的问题,即使在 .NET(这是您与 PowerShell 一起使用的)中,这里也有一篇关于您关心的 int->string 转换的精彩文章:http ://cc.davelozinski.com/c-sharp /fastest-way-to-convert-an-int-to-string

至于来自 AD 的字节数组转换,这是我所做的一个测试,并且通过显式转换为 a [string[]],我几乎总是看到使用 .tostring() 的好处。收益范围从 50% 到同等水平,但始终更快:

$s = [adsisearcher]'(&(objectCategory=user)(samaccountname=mysam))'
$r = @($s.FindAll())

(Measure-Command {
    foreach ($b in $r[0].Properties.userpassword[0]) {
        $b.tostring()
    }
}).TotalSeconds

(Measure-Command {
    [string[]]$r[0].Properties.userpassword[0]
}).TotalSeconds
Run Code Online (Sandbox Code Playgroud)

  • 澄清一下,`[string[]](1..1000000)` 比 `ForEach($i in 1..1000000) { $i.ToString() }` 快五倍。 (2认同)