Skip to content

Commit

Permalink
ByteBuffer: one fewer allocs to go to Data
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 committed Nov 23, 2024
1 parent 70dfce8 commit e7666f6
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 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,12 +126,10 @@ extension ByteBuffer {
count: Int(length)
)
} else {
_ = storageRef.retain()
return Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: ptr.baseAddress!.advanced(by: index)),
count: Int(length),
deallocator: .custom { _, _ in storageRef.release() }
)
let storage = storageRef.takeUnretainedValue()
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: ptr.baseAddress!.advanced(by: index)),
count: Int(length),
deallocator: .custom { _, _ in withExtendedLifetime(storage) {} })
}
}
}
Expand Down

0 comments on commit e7666f6

Please # to comment.