Skip to content

Instantly share code, notes, and snippets.

@lucaswkuipers
Created December 26, 2023 06:13
Show Gist options
  • Save lucaswkuipers/ba4df6faa184ddb4c9ebb5149bde46a7 to your computer and use it in GitHub Desktop.
Save lucaswkuipers/ba4df6faa184ddb4c9ebb5149bde46a7 to your computer and use it in GitHub Desktop.
Swift Array<T> count performance test comparison
import XCTest
// # Setup
// Big array size: 1_000_000_000 (1 billion elements of 12345)
// Small array size: 2 [12345, 12345]
// Loop: 1_000_000 (1 million) times.
// Machine: Macbook Pro 2023 16" M2 Max 32gb
// # Results
// TLDR: Stored: 3% faster
// Baseline (no operation, just the loop): 0.204s
// Small array Computed: 0.211s | Stored: 0.204s
// Big array: Computed: 0.213s | Stored: 0.203s (funny)
class ArrayCountPerformanceTests: XCTestCase {
let bigArray = Array(repeating: 12345, count: 1_000_000_000)
let smallArray = Array(repeating: 12345, count: 2)
let numnberOfLoops = 1_000_000
func test_baselinePerformance() {
measure {
for _ in 0...numnberOfLoops {
let _ = 1
}
}
}
func test_smallArray_computedCountPerformance() {
measure {
for _ in 0...numnberOfLoops {
let _ = smallArray.count
}
}
}
func test_smallArray_storedCountPerformance() {
measure {
let count = smallArray.count
for _ in 0...numnberOfLoops {
let _ = count
}
}
}
func test_bigArray_computedCountPerformance() {
measure {
for _ in 0...numnberOfLoops {
let _ = bigArray.count
}
}
}
func test_bigArray_storedCountPerformance() {
measure {
let count = bigArray.count
for _ in 0...numnberOfLoops {
let _ = count
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment