示例工程 12-opaque-existential-types

12-opaque-existential-types/Sources/Ch12Bench/App.swift

swift · 0.9 KB

import Ch12Kit
import Foundation
 
/// 同一份计算,两种调用路径:泛型(some)与存在类型(any)。
/// 用 `swift run -c release Ch12Bench` 运行;数字只用于本机对比。
@main
struct Ch12Bench {
    static func main() {
        let count = 1_000_000
        let concrete: [Circle] = (0..<count).map { Circle(radius: Double($0 % 10) + 1) }
        let existential: [any Shape] = concrete
 
        let clock = ContinuousClock()
        var checksum = 0.0
 
        let genericTime = clock.measure {
            for circle in concrete {
                checksum += circle.area()
            }
        }
 
        let existentialTime = clock.measure {
            for shape in existential {
                checksum += shape.area()
            }
        }
 
        print("generic: \(genericTime)")
        print("existential: \(existentialTime)")
        print("checksum: \(String(format: "%.3f", checksum))")
    }
}