Random generator

Is there a difference in the distribution of results between those 2 forms ?

let x = (1...9).randomElement()!

let y = Int.random(in: 1...9)

In doc, I never see the first form used

Answered by Claude31 in 737882022

I tested in simulator. Only difference seems to be that second form is 30% faster.

With 1 000 000 iterations, elapsed time is:

          let start1 = Date()
          for _ in 0...1000000 {
               let x = (1...9).randomElement()!
          }
          let elapsed1 = Date().timeIntervalSince(start1)
          print("elapsed1", elapsed1)

          let start2 = Date()
          for _ in 0...1000000 {
               let y = Int.random(in: 1...9)
          }
          let elapsed2 = Date().timeIntervalSince(start2)
          print("elapsed2", elapsed2)
elapsed1 1.2983139753341675
elapsed2 0.9677900075912476
Accepted Answer

I tested in simulator. Only difference seems to be that second form is 30% faster.

With 1 000 000 iterations, elapsed time is:

          let start1 = Date()
          for _ in 0...1000000 {
               let x = (1...9).randomElement()!
          }
          let elapsed1 = Date().timeIntervalSince(start1)
          print("elapsed1", elapsed1)

          let start2 = Date()
          for _ in 0...1000000 {
               let y = Int.random(in: 1...9)
          }
          let elapsed2 = Date().timeIntervalSince(start2)
          print("elapsed2", elapsed2)
elapsed1 1.2983139753341675
elapsed2 0.9677900075912476
Random generator
 
 
Q