From a2f1a8f1fa12ce58db2a85a747f5363a54492d3c Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Fri, 30 Apr 2021 15:42:04 +0100 Subject: [PATCH] ByteBuffer: one fewer allocs to go to Data Motivation: When getting a `Data` from a `ByteBuffer` we currently allocate twice (`__DataStorage`) and the closure for `Data.Deallocator`. Modifications: We can optimise that by making the closure capture exactly one `AnyObject` which is already a reference counted object. The compiler realises that (on Linux) and saves us an alloc. Thanks @lukasa for the suggestion here: https://github.com/apple/swift-nio/pull/1836#issuecomment-830044155 Result: Fewer allocs. --- Sources/NIOFoundationCompat/ByteBuffer-foundation.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift index 8b221d75cb..cf1a25830a 100644 --- a/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift +++ b/Sources/NIOFoundationCompat/ByteBuffer-foundation.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2024 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -126,11 +126,11 @@ extension ByteBuffer { count: Int(length) ) } else { - _ = storageRef.retain() + let storage = storageRef.takeUnretainedValue() return Data( bytesNoCopy: UnsafeMutableRawPointer(mutating: ptr.baseAddress!.advanced(by: index)), count: Int(length), - deallocator: .custom { _, _ in storageRef.release() } + deallocator: .custom { _, _ in withExtendedLifetime(storage) {} } ) } }