Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why execution time of "for($i=1; $i -le 1000000; $i++){}" faster than "for([int]$i=1; $i -le 1000000; $i++){}" in PowerShell

Tags:

powershell

Sample code:

# 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 question about differences between steps 2-6. But differences between 1 and 2 and 6 is inexplicable: $i in theese cases has type "System.Int32".

like image 830
speshuric Avatar asked Oct 31 '12 17:10

speshuric


1 Answers

If you want a good explanation of the difference between Step 1 and Step 2 just try at the command prompt :

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 confirm @zdan assumption the difference is in the cast that is done in every loop. Step 1 and 6 are the sames.

like image 142
JPBlanc Avatar answered Sep 30 '22 07:09

JPBlanc