0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellの配列、ArrayList、文字列、StringBuilderの速度をそれぞれ比較してみた。

Last updated at Posted at 2022-06-08

はじめに

ループで繰り返し追加するときに、配列や文字列を+=で拡張すると
パフォーマンスがよろしくないというのは割と常識となってますが、
じゃあどのぐらい差があるのかってあたりを比較してみました。

用意したもの

  • 郵便局提供の郵便番号データ(CSV)
  • PowerShell 5.1

比較対象

  • 配列
  • ArrayList
  • 文字列
  • StringBuilder

ソース

$data = Get-Content -Path ".\01HOKKAI.CSV"

Write-Output "Array"
$a = @()
ADD_Method $data $a

Write-Output "ArrayList"
$a = New-Object System.Collections.ArrayList
ADD_Method $data $a

Write-Output "String"
$a = ""
ADD_Method $data $a

Write-Output "StringBuilder"
$a = New-Object System.Text.StringBuilder
ADD_Method $data $a

function ADD_Method([object]$data,[object]$arr){
    $time = Get-Date
    foreach($d in $data){
        switch($arr.GetType().Name){
            ($_ -eq "Object[]" -or $_ -eq "String"){
                $arr += $d
            }
            "ArrayList"{
                $arr.Add($d) > $null
            }
            "StringBuilder"{
                $arr.Append($d) > $null
            }
        }
    }
    [Math]::Round(((Get-Date) - $time).TotalSeconds,3)
}

結果

PS C:\work\test> . "c:\work\test\Array.ps1"
Array
5.585
ArrayList
0.042
String
13.129
StringBuilder
0.065

結論

正直ここまで差が出るとは思わなかったw
そりゃまあループに組み込むならArrayListStringBuilder
一択になりますねw

おまけ

$data = [string[]](Get-Content -Path ".\01HOKKAI.CSV")

$time = Get-Date
$a = $data -join ""
[Math]::Round(((Get-Date) - $time).TotalSeconds,3)
PS C:\Extract\01hokkai> . "c:\Extract\01hokkai\Array.ps1"
0.042

-join 速ぇ!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?