Skip to content

Instantly share code, notes, and snippets.

@hironytic
Created June 12, 2022 08:58
Show Gist options
  • Select an option

  • Save hironytic/df777619df24f91947fcfbc654ca9609 to your computer and use it in GitHub Desktop.

Select an option

Save hironytic/df777619df24f91947fcfbc654ca9609 to your computer and use it in GitHub Desktop.
COW Problem
import Foundation
let arraySize = 1000000
let loopCount = 1000
class Values {
var values = [Int](repeating: 0, count: arraySize)
func foo1() {
values[0] += values[0]
}
func foo2() {
let v = values[0]
values[0] += v
}
}
func measure(_ body: () -> Void) {
let time1 = Date.timeIntervalSinceReferenceDate
for _ in 0 ..< loopCount {
body()
}
let time2 = Date.timeIntervalSinceReferenceDate
print(time2 - time1)
}
func f1() {
let v = Values()
measure { v.foo1() }
}
func f2() {
let v = Values()
measure { v.foo2() }
}
f1()
f2()
// 0.8569329977035522
// 0.001692056655883789
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment