0
1

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.

for/for in/forEach/enumeratedの処理速度について

Last updated at Posted at 2022-04-29

enumeratedも含めての処理速度についての記事が見当たらなかったので、実験を兼ねての投稿。

確認に使用するコード

        let array: [Int] = Array(0...10000)
        
        // for
        var start = Date()
        for i in 0 ..< array.count {
            print(i)
        }
        var elapsed = Date().timeIntervalSince(start)
        print("for : \(elapsed)")
        
        // for in
        start = Date()
        for i in array {
            print(i)
        }
        elapsed = Date().timeIntervalSince(start)
        print("for in : \(elapsed)")

        // forEach
        start = Date()
        array.forEach {
            print($0)
        }
        elapsed = Date().timeIntervalSince(start)
        print("forEach : \(elapsed)")
        
        // enumerateObjectsUsingBlock
        start = Date()
        for (_, value) in array.enumerated() {
            print(value)
        }
        elapsed = Date().timeIntervalSince(start)
        print("enumerated : \(elapsed)")

結果はコンソールログで確認。

ログ1回目

for : 0.056269049644470215
for in : 0.04717898368835449
forEach : 0.04207801818847656
enumerated : 0.038896918296813965

ログ2回目

for : 0.04687905311584473
for in : 0.03984999656677246
forEach : 0.03262805938720703
enumerated : 0.03680300712585449

ログ3回目

for : 0.07473194599151611
for in : 0.041075944900512695
forEach : 0.04214298725128174
enumerated : 0.040978074073791504

結果

for以外はそこまで処理速度に違いはないと感じたので、好きなものを使用して大丈夫そうという所感。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?