Created
June 12, 2022 08:58
-
-
Save hironytic/df777619df24f91947fcfbc654ca9609 to your computer and use it in GitHub Desktop.
COW Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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