Currently to get a UnsafeBufferPointer or Span out of a String without requiring too high of a platforms requirement, you need code similar to the following for maximum performance:
@available(SwiftStdlib 5.1, *)
extension String {
/// Calls `body` with a `Span` of this String's utf8 bytes.
@inlinable
@inline(always)
func withSpan_Compatibility<T>(
_ body: (Span<UInt8>) -> T
) -> T {
/// Fast path: Currently always the case for non-Darwin.
/// On Darwin, always the case unless for some objc-bridged strings.
if let fastResult = self.utf8.withContiguousStorageIfAvailable({ buffer in
body(unsafe buffer.span)
}) {
return fastResult
}
return self.withSpan_Compatibility_SlowPath(body)
}
/// This function can only be reached on Darwin and only for some objc-bridged strings.
/// Therefore it's not worth inlining. As a matter of fact it's worth forcing it to not inline at all.
@usableFromInline
@inline(never)
func withSpan_Compatibility_SlowPath<T>(
_ body: (Span<UInt8>) -> T
) -> T {
/// Same availability guard as `utf8Span` has in swift repo.
/// The symbol is available there but will just abort.
#if !(os(watchOS) && _pointerBitWidth(_32))
if #available(SwiftStdlib 6.2, *) {
return body(self.utf8.span)
}
#endif
var copy = self
return copy.withUTF8 { buffer in
body(unsafe buffer.span)
}
}
}
(Edit: self.utf8Span.span was changed to self.utf8.span per discussion below)
I'd expect Swift to provide this by itself.
I've seen code similar to this countless times. In swift-nio packages or swift-foundation. Even there sometimes it's held wrong and used in a suboptimal way (performance wise), and all those aside, not even any of swift-nio or swift-foundation packages use the faster utf8Span path for objc-bridged strings.
Outside of Apple repos you also cannot expect anybody to actually know to do this. Even well-known people like the author of swift-yyjson isn't holding string right in a package he presumably created to squeeze more performance out of Codable, and I cannot blame him.
utf8Span not only requires macOS 26 which is too high, but also is not the most performant way to access a non-objc-bridged string's UTF8 bytes anyway.
Is it time for stdlib to remedy the situation and provide back-deployed ways to properly get a span out of a String? I can also help with the implementation if the idea is sound.
I guess out of context it does look weird, but the general home-made convention I’m following is to use _Compatibility in the name where the function is for the most part being used as a compatibility layer.
Here these functions are a compatibility layer over utf8Span, although the “with contiguous storage” function is also faster in cases.
I don't think I knew this: utf8Span.span really is less performant than unsafe APIs in getting a Span? That seems like a problem: it doesn't make sense that we are having to detour through unsafe APIs just to get a Span faster.
While being able to use APIs more widely is nice, backdeployment is out of the scope of Swift Evolution and a decision reserved for the platform vendor.
The smaller part of the issue is that yes, it is slightly less performant. Now I don’t recall the details 100% since it’s been a few months, but I think it was related to the _SmallString being copied around in utf8Span where the .utf8.contiguousStorage API wouldn’t. So a small performance loss.
The bigger issue is though that the @available attributes cost a decent amount, so if you need to wrap utf8Span in @available then it becomes a much more noticeable perf loss.
I’m always fine if you think you should change the category of the post or such. I have no big preference and as I’ve mentioned to others in Discord server contexts, I think having many categories and all is confusing for a user (sometimes even intimidating, for a beginner).
Otherwise I think this is a discussion that’s still worth having, given that I don’t think it’s technically any difficult to actually implement this, after all all the underlying APIs have been available for a long time and this can just be a @_alwaysEmitIntoClient or @export(implementation). I think the bigger blocker here is to find a proper API shape for it. I believe with some hacky code you can even turn the whole closure into another var, like “var utf8Bytes”. Might take a few builtins and experimental features like how InlineArray.span is implemented, but should be possible.
I would expect a very small amount of overhead in UTF8Span related to bounds-checking and just the cost of moving data in registers to construct the value, but it should not be slower than a buffer pointer in general usage; if you're seeing it is slower, that's absolutely worth filing issues. We don't want to be in a position where people are discouraged from using the safe API because it's a major perf hit.
As for @available (I assume you mean if #available?), there is certainly a non-zero runtime cost to doing the availability check but it should be amortized over repeated calls. If you're seeing it make a deep call into the OS on every usage, please file issues for that too. Availability checks should not be a significant bottleneck with optimizations on. (If it turns out to be something that for whatever reason can't be optimized away, there are strategies you can use to reduce the number of calls you make, of course.)
The underlying OS APIs that if #available compile down to (provided by compiler-rt) are more expensive than you might imagine, even when amortized over many calls. There was some work done to improve it in recent Apple OS releases, but I would still expect if #available statements that cannot be optimized away entirely to have measurable cost for extremely perf sensitive code if the code is organized in such a way where it must be called repeatedly. It would not surprise me at all to see availability checks dominating a trace for code that works with a type like UTF8Span where most of the code is otherwise already inlined. While there is always more that can be done, I think most of the low-hanging fruit has already been picked for the existing ABI for if #available.
Oh trust me, I'm aware of the cost of the underlying calls. But we could still eliminate the recurring costs and properly amortize the initial costs by emitting a dispatch_once() (well, swift_once()) call around the check, since the OS version won't change over the lifetime of the process. Honestly, I'm surprised that we don't do that already.
We could go further and emit a singledispatch_once-guarded check that gets the OS version and then, for every #available, emit the equivalent of if cachedVersion >= statedVersionInSourceCodeHere instead, which could be optimized down to a single compare-and-branch if we have our druthers.
Not to get too deep into a specific implementation though: my point is simply that if this language feature is slow, we should try to improve it rather than discouraging adoption of new API.
I don't recall why exactly I have not already filed an issue for this exact case. I typically do file issues. Nowadays I file more PRs than issue as my understanding of the compiler is growing (and the "frontier" LLMs are of good help, to save time if nothing else, personally). I'll check it again soon. But generally I've seen multiple instances of things being copied on the stack when they don't need to, when interacting with the newer types (non-copyable/escapable, both), and I believe some Swift-team folks are aware of such issue as I've seen discussions here on the forums about them.
I did file an issue for this one and thanks to @tshortli (I think so at least, I can't see past feedback assistant) things should be better.
I never re-benchmarked stuff to compare. Nowadays I typically run the opposite direction as soon as I see a #available, as I'm mostly working on performance sensitive code where 1ns less is considered a nice improvement (that's what I was doing for most of yesterday. Lowering some operation down, from ~4.8 to ~3.8ns or so).
Right. I did try some, after I filed the issue above, such as trying to make less calls (simplest form of which is to hoist #available out of a loop for example). However at the point where I had to look for better "strategies", I chose .utf8.withContiguousStorageIfAvailable as the best one.
Adding the span property to String.UTF8View required runtime support, and that is why it requires macOS 26.
We could possibly provide an Optional<Span> property, but the demand for that has been substantially less urgent than for other span improvements. I do think it would be helpful.
Apart from that, here are some benchmark run results (unaffected by the issue mentioned above):
Darwin (M1) vs Linux (AMD EPYC-Milan, x86_64); .utf8Span.span vs .utf8.withContiguousStorageIfAvailable;
string
Darwin UTF8Span
UTF8View
Linux UTF8Span
UTF8View
10 bytes; immortal
4.34 ns
1.55 ns
5.19 ns
2.18 ns
10 bytes; small
4.34 ns
1.86 ns
5.20 ns
2.45 ns
20 bytes; immortal
4.34 ns
2.17 ns
5.21 ns
2.46 ns
20 bytes; large
4.34 ns
2.17 ns
5.19 ns
2.18 ns
So 2-3 times slower for the usage itself. I'd say this is negligible for most usecases.
/// From external module, like e.g. package-benchmark
/// Otherwise could be optimized away
@inline(never) @_optimize(none) func blackHole
func utf8Span(string: String) {
let bytes = string.utf8Span.span
blackHole(bytes)
}
func utf8View(string: String) {
string.utf8.withContiguousStorageIfAvailable {
let bytes = $0.span
blackHole(bytes)
}.unsafelyUnwrapped
}
Sidenote: I had never noticed there is a span property on UTF8View as well. It doesn't change much though; it's somewhere between .utf8Span and .utf8.withContiguous... in terms of perf (3.8ns on Linux).
Sometimes. I don't remember the details at the assembly level, but I remember that the resulting __text section when using Span was sometimes larger than calling withUnsafe, as was the number of instructions. I assume this is due to the optimizer, since in other cases the size was the same (which, of course, doesn't mean the instructions were identical).
PS: (a bit offtopic)
However, there’s also a positive flip side – calling the new initializer String(copying: UTF8Span(unchecked: span, isKnownASCII: true)) is incredibly compact in terms of internal machinery when building for embedded systems. As far as I recall it’s about 1 KB smaller compared to String(validating: , as: UTF8.self). Other initializers are significantly heavier.
That sounds weird and unexpected, I wonder if there were any other factors in play.
It's likely because that initializer does not repair the UTF8 if it's ill-formed. So it's not safe to use when you're not 100% sure that span is valid UTF8 (no surrogates or out of bounds scalars, no ill-formed sequence of bytes).
That's because it's trusting that a UTF8Span is indeed in valid UTF8, but you're bypassing that when you use the UTF8Span(unchecked:) initializer as UTF8Span won't double-check/repair the bytes anymore.
That's true for the most part but it doesn't help anything.