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

标签 string performance powershell int type-conversion

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

$i = 5
$i.ToString()

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

PS I:\ADCC\Scripting Performance> .\int_to_str.ps1
6.747561
PS I:\ADCC\Scripting Performance> .\int_to_str.py
0.37243021680382793

我正在使用 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

这是int_to_str.ps1的内容:

(Measure-Command {
    ForEach($i in 1..1000000){
        $i.ToString()
    }
}).TotalSeconds

这是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)

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

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

最佳答案

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

就 AD 的字节数组转换而言,这是我所做的一个测试,通过显式转换为 [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

关于string - PowerShell 将整数转换为字符串的速度很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44767661/

相关文章:

swift - 将 Int 转换为格式化字符串(Swift)

c++ - 使用 getline 读取文件/输入时出现段错误

c# - ar-sa 文化的预期日期时间字符串是什么?

javascript - iFrame - 在 Web 应用程序中实现 Iframe 的成本

电源外壳。无法从 {} 获取变量

regex - 如何在powershell中使用正则表达式获取所有匹配字符串的列表?

ruby - 仅将 1 添加到 ruby​​ 数组中的整数

javascript - 纯JavaScript中的表单处理和验证

java - 使用 G1 时,大量 Activity 实例的分配性能会降低吗?

powershell - Azure 资源模板参数 hell