Last active
May 21, 2021 03:13
-
-
Save ethanhuang13/b1d4216ae815b1ceec05fbf0a0b2dbf3 to your computer and use it in GitHub Desktop.
ClampTests
This file contains 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
// A challenge from https://twitter.com/hanyu_chen_ios/status/1395533041989079045 | |
// Screenshots of performance tests https://twitter.com/ethanhuang13/status/1395577548151541760?s=21 | |
import XCTest | |
let maxValue = 100 | |
let minValue = 0 | |
final class ClampTests: XCTestCase { | |
func testMeasureNaiveCompare() throws { | |
measure { | |
for _ in 0 ..< 1_000_000 { | |
let random = Int.random(in: -100 ... 200) | |
let _: Int = { | |
if random > maxValue { | |
return maxValue | |
} else if random < minValue { | |
return minValue | |
} else { | |
return random | |
} | |
}() | |
} | |
} | |
} | |
func testMeasureFuncMinMax() throws { | |
measure { | |
for _ in 0 ..< 1_000_000 { | |
let random = Int.random(in: -100 ... 200) | |
_ = min(max(random, minValue), maxValue) | |
} | |
} | |
} | |
func testMeasureFuncMaxMin() throws { | |
measure { | |
for _ in 0 ..< 1_000_000 { | |
let random = Int.random(in: -100 ... 200) | |
_ = max(min(random, maxValue), minValue) | |
} | |
} | |
} | |
func testMeasureSwitch() throws { | |
measure { | |
for _ in 0 ..< 1_000_000 { | |
let random = Int.random(in: -100 ... 200) | |
let _: Int = { | |
switch random { | |
case _ where random > maxValue: return maxValue | |
case _ where random < minValue: return minValue | |
default: return random | |
} | |
}() | |
} | |
} | |
} | |
func testMeasureIsThisSlower() throws { | |
measure { | |
for _ in 0 ..< 1_000_000 { | |
let random = Int.random(in: -100 ... 200) | |
let _: Int = [minValue, random, maxValue].sorted()[1] | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment