Last active
January 29, 2018 13:00
-
-
Save mlcollard/a649b0ac7d3cbef1c53046e739b8b42a to your computer and use it in GitHub Desktop.
iOS: Compare class and struct timing
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
// | |
// ClassStructTiming.swift | |
// | |
// Compare class and struct timing | |
// | |
// Derived from https://github.com/knguyen2708/StructVsClassPerformance | |
import Foundation | |
class IntClass { | |
var value: Int | |
init(_ val: Int) { self.value = val } | |
} | |
struct IntStruct { | |
var value: Int | |
init(_ val: Int) { self.value = val } | |
} | |
func + (x: IntClass, y: IntClass) -> IntClass { | |
return IntClass(x.value + y.value) | |
} | |
func + (x: IntStruct, y: IntStruct) -> IntStruct { | |
return IntStruct(x.value + y.value) | |
} | |
// 10 fields | |
class Int10Class { | |
var value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int | |
init(_ val: Int) { | |
self.value1 = val | |
self.value2 = val | |
self.value3 = val | |
self.value4 = val | |
self.value5 = val | |
self.value6 = val | |
self.value7 = val | |
self.value8 = val | |
self.value9 = val | |
self.value10 = val | |
} | |
} | |
struct Int10Struct { | |
var value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int | |
init(_ val: Int) { | |
self.value1 = val | |
self.value2 = val | |
self.value3 = val | |
self.value4 = val | |
self.value5 = val | |
self.value6 = val | |
self.value7 = val | |
self.value8 = val | |
self.value9 = val | |
self.value10 = val | |
} | |
} | |
func + (x: Int10Struct, y: Int10Struct) -> Int10Struct { | |
return Int10Struct(x.value1 + y.value1) | |
} | |
func + (x: Int10Class, y: Int10Class) -> Int10Class { | |
return Int10Class(x.value1 + y.value1) | |
} | |
func measure(_ name: String, block: () -> ()) -> Double { | |
let t0 = Date() | |
block() | |
let ft = Date().timeIntervalSince(t0) | |
print("\(name) -> \(ft)") | |
return ft | |
} | |
func runTests() { | |
let c1t = measure("class (1 field)") { | |
var x = IntClass(0) | |
for _ in 1...10000000 { | |
x = x + IntClass(1) | |
} | |
} | |
let s1t = measure("struct (1 field)") { | |
var x = IntStruct(0) | |
for _ in 1...10000000 { | |
x = x + IntStruct(1) | |
} | |
} | |
let ratio1 = c1t / s1t | |
print("class/struct = \(ratio1)") | |
let c10t = measure("class (10 fields)") { | |
var x = Int10Class(0) | |
for _ in 1...10000000 { | |
x = x + Int10Class(1) | |
} | |
} | |
let s10t = measure("struct (10 fields)") { | |
var x = Int10Struct(0) | |
for _ in 1...10000000 { | |
x = x + Int10Struct(1) | |
} | |
} | |
let ratio10 = c10t / s10t | |
print("class/struct = \(ratio10)") | |
} | |
runTests() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment