 
 extension NSLock {
     func sync<T>(_ closure: () -> T) -> T {
-        lock(); defer { unlock() }
+        lock(); defer { unlock() };
         return closure()
     }
 }
 
-private final class Handlers<T> { // boxed handlers
-    var fulfill = [(T) -> Void]()
-    var reject = [(Error) -> Void]()
+private struct Handlers<T> { // boxed handlers
+    var fulfill = ContiguousArray<(T) -> Void>()
+    var reject = ContiguousArray<(Error) -> Void>()
 }
 
 private enum Result<T> {
     case fulfilled(T), rejected(Error)
-    /// Returns a `value` if the result is success.
 
     var value: T? {
         if case let .fulfilled(val) = self { return val } else { return nil }
     }
 
-    /// Returns an `error` if the result is failure.
     var error: Error? {
         if case let .rejected(err) = self { return err } else { return nil }
     }

/// Promises start in a *pending* state and either get *fulfilled* with a
/// value or get *rejected* with an error.
public final class Promise<T> {
    // previous `State` based approach was easier to reason about but was
    // harder to implement in a performant way.
    private var handlers: Handlers<T>? // nil when finished
    private var result: Result<T>? // nil when pending


    /// or `reject` when it completes.
    public init(_ closure: (_ fulfill: @escaping (T) -> Void, _ reject: @escaping (Error) -> Void) -> Void) {
        handlers = Handlers<T>()
        closure({ self._fulfill($0) }, { self._reject($0) }) // retain self
    }
    
    private func _fulfill(_ value: T) {
        _resolve(.fulfilled(value))?.fulfill.forEach { $0(value) }
    }

    private func _reject(_ error: Error) {
        _resolve(.rejected(error))?.reject.forEach { $0(error) }
    }

    // Return handlers to call if promise was resolved. Returns nil otherwise.
    private func _resolve(_ result: Result<T>) -> Handlers<T>? {
        _lock.lock(); defer { _lock.unlock() }
        guard self.result == nil else { return nil } // already resolved
        self.result = result
        let handlers = self.handlers
        self.handlers = nil
        return handlers // returns handlers to be used outside of critical section
    }

    /// Creates a promise fulfilled with a given value.
