I saw an article serde's borrowing can be treacherous and I was curious about the performance impact of using Cow<'a, str> instead of String as I have always used String in my code because it is very convenient. The article suggested using Cow<'a, str> as a potential solution to avoid unnecessary allocations. While it may seem like it makes perfect sense to not allocate when possible, this benchmark aims to evaluate whether using Cow<'a, str> actually provides a performance benefit over using String directly.
All code can be found on Github.
# Benchmark Setup
The benchmark is run using the criterion crate. The benchmark is run with the following parameters:
NUM_OBJECTS: 1,000,000STRING_SIZE: 200
JSON is generated using the following methods:
generate_happy_path_json: Generates a JSON array of objects with simple strings (happy path - no escaping needed)generate_partial_escaped_json: Generates a JSON array where some objects have escaped stringsgenerate_pathological_json: Generates a JSON array where all objects have escaped strings (pathological case)
# Machine
- CPU: AMD Ryzen 7 5800X3D @ 4.5GHz
- RAM: 32GB DDR4 3200MHz
- Storage: WD_BLACK SN850X 1TB NVMe SSD
- Kernel: 6.17.9-arch1-1
# Formatted Results
# Happy Path (No Escaping Needed)
| Implementation | Lower Bound | Estimate | Upper Bound | vs String |
|---|---|---|---|---|
String | 144.07 ms | 144.19 ms | 144.30 ms | baseline |
Cow<'a, str> | 97.999 ms | 98.089 ms | 98.178 ms | 38.0561% faster |
&'a str | 96.199 ms | 96.261 ms | 96.315 ms | 39.8659% faster |
# Partial Escaped (Some Objects Need Escaping)
| Implementation | Lower Bound | Estimate | Upper Bound | vs String |
|---|---|---|---|---|
String | 163.01 ms | 163.16 ms | 163.30 ms | baseline |
Cow<'a, str> | 135.03 ms | 135.15 ms | 135.27 ms | 18.7791% faster |
# Pathological Case (All Objects Need Escaping)
| Implementation | Lower Bound | Estimate | Upper Bound | vs String |
|---|---|---|---|---|
String | 180.97 ms | 181.08 ms | 181.18 ms | baseline |
Cow<'a, str> | 182.37 ms | 182.55 ms | 182.75 ms | 0.808% slower |