Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ethanhuang13
Last active May 21, 2021 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethanhuang13/b1d4216ae815b1ceec05fbf0a0b2dbf3 to your computer and use it in GitHub Desktop.
Save ethanhuang13/b1d4216ae815b1ceec05fbf0a0b2dbf3 to your computer and use it in GitHub Desktop.
ClampTests
// 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