Skip to content

Commit 7fa8d19

Browse files
committed
how to return arrays from functions to not cause performance issues
1 parent 4904e0a commit 7fa8d19

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

good-practices/return.ps1

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
Clear-Host
2+
$tmpFile = 'd:\temp\tmp.mp4'
3+
4+
function Get-Obj {
5+
[byte[]]$payload = [System.IO.File]::ReadAllBytes($tmpFile)
6+
$payload
7+
}
8+
9+
function Get-Wrapped {
10+
[byte[]]$payload = [System.IO.File]::ReadAllBytes($tmpFile)
11+
@{ wrap = $payload }
12+
}
13+
14+
function Get-Operator {
15+
[byte[]]$payload = [System.IO.File]::ReadAllBytes($tmpFile)
16+
,$payload
17+
}
18+
19+
function Get-WriteOutput {
20+
[byte[]]$payload = [System.IO.File]::ReadAllBytes($tmpFile)
21+
Write-Output $payload -NoEnumerate
22+
}
23+
24+
Measure-Command {
25+
[byte[]]$out1 = Get-Obj
26+
Write-Host "Size: $($out1.Length)"
27+
}
28+
29+
Measure-Command {
30+
$out2 = Get-Wrapped
31+
Write-Host "Size: $($out2.wrap.Length)"
32+
}
33+
34+
Measure-Command {
35+
$out3 = Get-Operator
36+
Write-Host "Size: $($out3.Length)"
37+
}
38+
39+
Measure-Command {
40+
$out4 = Get-WriteOutput
41+
Write-Host "Size: $($out4.Length)"
42+
}
43+
44+
# OUTPUT for 6.5 MB file
45+
46+
##### Get-Obj #####
47+
# Size: 6 439 243
48+
# TotalSeconds : 2.4369009
49+
# TotalMilliseconds : 2436.9009
50+
51+
##### Get-Wrapped #####
52+
# Size: 6 439 243
53+
# TotalSeconds : 0.0087145
54+
# TotalMilliseconds : 8.7145
55+
56+
##### Get-Operator #####
57+
# Size: 6 439 243
58+
# TotalSeconds : 0.025268
59+
# TotalMilliseconds : 25.268
60+
61+
##### Get-WriteOutput #####
62+
# Size: 6 439 243
63+
# TotalSeconds : 0.0205171
64+
# TotalMilliseconds : 20.5171

0 commit comments

Comments
 (0)