`InlineString' is a proof of concept exploring a fixed-capacity UTF-8 string representation optimized for small strings.
The goal of this project is to investigate whether storing short strings directly inside a value type can provide performance and memory-layout benefits compared to Swift's general-purpose String.
Stores up to 16 UTF-8 bytes directly inside the value.
Creating from string literal:
let city: InlineString16 = "Berlin"Creating from String:
let string: String = "Tokyo"
let location = InlineString16(string)Creating from String with capacity validation:
let string: String = "Hanoi"
guard let place = InlineString16(validating: string) else {
// String exceeds capacity
}- Bitwise-copyable value type
- No heap allocation for stored content
- Fixed capacity: 16 UTF-8 bytes
- Inline UTF-8 byte storage using two
UInt64values - Fast copying and equality checks
- Protocol conformances:
BitwiseCopyableSendableEquatableHashableCodableExpressibleByStringLiteralCustomStringConvertibleCustomDebugStringConvertible
InlineString16 stores up to 16 UTF-8 bytes:
┌───────────────┬───────────────┐
│ UInt64 │ UInt64 │
│ bytes 0...7 │ bytes 8...15 │
└───────────────┴───────────────┘
The string length is stored as metadata inside the representation.
Important
When the storage is not fully utilized, the last byte is reserved for storing the string length. As a result, the final UTF-8 byte of the string cannot be in the range 0x00...0x0F, since those values are reserved for the length encoding.
InlineString16 is optimized for small fixed-size strings.
- Advantages:
- Compact storage
- Predictable memory layout
- Fast copying
- Fast iteration
- Limitations:
- Maximum size is 16 UTF-8 bytes
- Converting back to
Stringrequires creating aStringvalue - Not intended as a replacement for general-purpose
String - Last UTF-8 byte cannot be in the range
0x00...0x0F, as these values are reserved for encoding the string length
Good use cases for InlineString16:
- Identifiers
- Keys
- Tags
- Event names
- Small fixed-size values
InlineString16 is not intended to:
- replace Swift
String; - support arbitrary-length strings;
- provide the full
StringAPI; - optimize Unicode processing.
Add the following dependency to your Package.swift:
.package(url: "https://github.com/0xdea110c8/InlineString.git", from: "0.1.0")Then add InlineString to your target dependencies.
This project is licensed under the MIT License. See LICENSE for details.