Skip to content

Commit

Permalink
ByteBuffer: one fewer allocs to go to Data (#1839)
Browse files Browse the repository at this point in the history
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:
#1836 (comment)

Result:

Fewer allocs.
  • Loading branch information
weissi authored Nov 26, 2024
1 parent 848e428 commit d6be946
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Sources/NIOFoundationCompat/ByteBuffer-foundation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {} }
)
}
}
Expand Down

0 comments on commit d6be946

Please sign in to comment.