ZEON256 ZEON256
← BACK

Serde Cow<'a, str> vs String Performance

ZEON256
ZEON256 2025-12-27 2 min read
rust serde performance benchmark
Target Audience Rust developers Backend developers Performance engineers
AI Summary
Benchmarking Cow<'a, str> vs String vs &'a str for serde deserialization. Cow is ~38% faster on the happy path and ~19% faster with partial escaping, but marginally slower in the pathological case where everything needs escaping.

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,000
  • STRING_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 strings
  • generate_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)

ImplementationLower BoundEstimateUpper Boundvs String
String144.07 ms144.19 ms144.30 msbaseline
Cow<'a, str>97.999 ms98.089 ms98.178 ms38.0561% faster
&'a str96.199 ms96.261 ms96.315 ms39.8659% faster

Partial Escaped (Some Objects Need Escaping)

ImplementationLower BoundEstimateUpper Boundvs String
String163.01 ms163.16 ms163.30 msbaseline
Cow<'a, str>135.03 ms135.15 ms135.27 ms18.7791% faster

Pathological Case (All Objects Need Escaping)

ImplementationLower BoundEstimateUpper Boundvs String
String180.97 ms181.08 ms181.18 msbaseline
Cow<'a, str>182.37 ms182.55 ms182.75 ms0.808% slower