Created
August 13, 2016 05:21
-
-
Save andersio/f6af7b65a99cccbe77acb5fdbaf67303 to your computer and use it in GitHub Desktop.
LenseTest
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
| // | |
| // Inlining.swift | |
| // Benchmarks | |
| // | |
| // Created by Anders on 13/8/2016. | |
| // Copyright © 2016 Anders. All rights reserved. | |
| // | |
| import XCTest | |
| struct SuperStruct { | |
| var field0 = 0 | |
| var field1 = 1 | |
| var field2 = 2 | |
| var field3 = 3 | |
| var field4 = 4 | |
| var field5 = 5 | |
| var field6 = 6 | |
| var field7 = 7 | |
| } | |
| class Inlining: XCTestCase { | |
| func testPerformanceInlined() { | |
| let value = TestAtomic(SuperStruct()) | |
| var isValueCorrect = true | |
| measure { | |
| for _ in 0 ..< 1000000 { | |
| isValueCorrect = isValueCorrect && value.withValue { $0.field1 } == 1 | |
| } | |
| XCTAssert(isValueCorrect) | |
| } | |
| } | |
| func testPerformanceNormal() { | |
| let value = TestAtomic(SuperStruct()) | |
| let lense = test(value: value) | |
| var isValueCorrect = true | |
| measure { | |
| for _ in 0 ..< 1000000 { | |
| isValueCorrect = isValueCorrect && lense() == 1 | |
| } | |
| XCTAssert(isValueCorrect) | |
| } | |
| } | |
| func testPerformanceValueLense() { | |
| let value = TestAtomic(SuperStruct()) | |
| let lense = test2(value: value) | |
| var isValueCorrect = true | |
| measure { | |
| for _ in 0 ..< 1000000 { | |
| isValueCorrect = isValueCorrect && lense.value == 1 | |
| } | |
| XCTAssert(isValueCorrect) | |
| } | |
| } | |
| } | |
| public final class ValueLense { | |
| let _atomic: TestAtomic<SuperStruct> | |
| var value: Int { | |
| return _atomic.withValue { $0.field1 } | |
| } | |
| init(_ atomic: TestAtomic<SuperStruct>) { | |
| _atomic = atomic | |
| } | |
| } | |
| func test(value: TestAtomic<SuperStruct>) -> () -> Int { | |
| return { value.withValue { $0.field1 } } | |
| } | |
| func test2(value: TestAtomic<SuperStruct>) -> ValueLense { | |
| return ValueLense(value) | |
| } | |
| public final class TestAtomic<Value> { | |
| private var _value: Value | |
| public init(_ value: Value) { | |
| _value = value | |
| } | |
| // @inline(__always) | |
| public func inlinedWithValue<Result>(_ action: @noescape (inout Value) throws -> Result) rethrows -> Result { | |
| return try action(&_value) | |
| } | |
| // @inline(never) | |
| public func withValue<Result>(_ action: @noescape (Value) throws -> Result) rethrows -> Result { | |
| return try action(_value) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment