[swift-users] Optimal String conversion to/from UTF-8 w/o null-termination?

Quinn "The Eskimo!" eskimo1 at apple.com
Mon Nov 6 08:58:42 CST 2017

On 3 Nov 2017, at 19:42, Jens Alfke via swift-users <swift-users at swift.org> wrote:

> Any way to pass the bytes directly to String without an intermediate copy?

You can do this with `UnsafeBufferPointer`.  For example:

extension String {
    init?(bytes: UnsafePointer<UInt8>, count: Int) {
        let bp = UnsafeBufferPointer(start: bytes, count: count)
        self.init(bytes: bp, encoding: .utf8)

I don’t know if this is faster.

There are lots of different ways to achieve your two goals and I wouldn’t even start optimising this without a realistic model of what your strings look like in practice, and a performance test based on that model.

Share and Enjoy
Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

More information about the swift-users mailing list