示例代码:
# Step 1
$start = get-date
for($i=1; $i -le 1000000; $i++){}
$end = get-date
($end-$start).TotalMilliseconds
Remove-Variable i
# Step 2
$start = get-date
for([int]$i=1; $i -le 1000000; $i++){}
$end = get-date
($end-$start).TotalMilliseconds
Remove-Variable i
# Step 3
$start = get-date
for([int64]$i=1; $i -le 1000000; $i++){}
$end = get-date
($end-$start).TotalMilliseconds
Remove-Variable i
# Step 4
$start = get-date
for([float]$i=1; $i -le 1000000; $i++){}
$end = get-date
($end-$start).TotalMilliseconds
Remove-Variable i
# Step 5
$start = get-date
for([double]$i=1; $i -le 1000000; $i++){}
$end = get-date
($end-$start).TotalMilliseconds
Remove-Variable i
# Step 6
$start = get-date
for($i=1; $i -le 1000000; $i++){}
$end = get-date
($end-$start).TotalMilliseconds
Remove-Variable i
Run Code Online (Sandbox Code Playgroud)
结果:
1845.1056
3160.1808
5029.2877
5521.3158
4504.2576
1804.1032
毫无疑问,步骤2-6之间存在差异.但是1和2和6之间的差异是莫名其妙的:在这种情况下,$ i的类型为"System.Int32".
如果您想清楚地解释步骤 1 和步骤 2 之间的差异,只需尝试在命令提示符处:
Remove-Variable i
Trace-Command -Name TypeConversion -Expression {for($i=1; $i -le 1000000; $i++){}} -PSHost
Run Code Online (Sandbox Code Playgroud)
进而 :
Remove-Variable i
Trace-Command -Name TypeConversion -Expression {for([int]$i=1; $i -le 1000000; $i++){}} -PSHost
Run Code Online (Sandbox Code Playgroud)
这证实了 @zdan 的假设,差异在于每个循环中完成的转换。步骤 1 和 6 相同。