Why is the run time "for ($ i = 1; $ i -le 1,000,000; $ i ++) {}" faster than "for ([int] $ i = 1; $ i -le 1,000,000; $ i ++) {} "in PowerShell

Code example:

# 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 

Results:

1845.1056
3160.1808
5029.2877 5521.3158

4504.2576 1804.1032

There are no questions about the differences between steps 2-6. But the differences between 1 and 2 and 6 are inexplicable: $ i in these cases is of type "System.Int32".

+7
source share
1 answer

If you want a good explanation of the difference between steps 1 and 2, just try the command line:

 Remove-Variable i Trace-Command -Name TypeConversion -Expression {for($i=1; $i -le 1000000; $i++){}} -PSHost 

And then:

 Remove-Variable i Trace-Command -Name TypeConversion -Expression {for([int]$i=1; $i -le 1000000; $i++){}} -PSHost 

This confirms @zdan's assumption that the difference is what is done in each loop. Step 1 and 6 are the names.

+4
source

All Articles