`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.
Benchmarks were performed against Swift String. Each benchmark was executed repeatedly to obtain stable measurements.
| Benchmark | String |
InlineString16 |
Result |
|---|---|---|---|
| Copy | 3.12 ms | 0.67 ms | ~4.7x faster |
| Array iteration | 3.11 ms | 0.69 ms | ~4.5x faster |
| Equality (different values) | 1.80 ms | 0.70 ms | ~2.6x faster |
| Array search | 6.36 ms | 4.03 ms | ~1.6x faster |
| Accessing count | 0.68 ms | 0.67 ms | Comparable performance |
| Hashing | 15.16 ms | 15.23 ms | Comparable performance |
| Decoding | 379 ms | 373 ms | Comparable performance |
| Encoding | 350 ms | 363 ms | Comparable performance |
| Initialization | 3.10 ms | 4.72 ms | ~1.5x slower |
| Initialization (16-byte strings) | 3.12 ms | 7.12 ms | ~2.3x slower |
Conversion to String |
3.11 ms | 9.02 ms | ~2.9x slower |
InlineString16 is optimized for small fixed-size strings.
- Advantages:
- Compact storage
- Predictable memory layout
- Fast copying
- Fast comparison
- 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
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.