Design a Small-String-Optimized Buffer in C++
System DesignModel answerLast updated
Evaluate low-level C++ skills: memory layout, copy semantics, alignment/padding, and how SSO eliminates heap allocations for short strings.
Background
Many real-world C++ runtimes avoid heap allocations for short strings by storing the characters inline inside the object itself. This is called small-string optimization (SSO). Below is a simplified starting point that demonstrates the idea but leaves several performance and correctness problems on the table.
const size_t BUFF_SIZE = 128;
class MyString {
private:
char buf[BUFF_SIZE]; // inline storage for short strings
size_t length; // character count, not including the null terminator
char* ptr; // heap pointer for long strings
public:
MyString(const char* s, size_t len) {
length = len;
if (len < BUFF_SIZE) {
strncpy(buf, s, len);
buf[len] = '\0';
} else {
ptr = (char*)malloc(len + 1);
if (ptr == nullptr) throw "not enough memory";
memcpy(ptr, s, len);
ptr[len] = '\0';
}
}
};
Questions
-
Copy speed.
strncpy(buf, s, len)copies characters in a byte-by-byte loop. What would you use instead, and why is it faster for short strings? -
memcpyvsstrncpy. Switching tomemcpy(buf, s, len)is not a drop-in replacement. What are the behavioral differences, and what safety pitfalls does each introduce? -
Comparison performance. In a string-comparison function, why can comparing short strings (under 256 bytes) be significantly faster than comparing long ones — even if you set aside the fact that they have fewer characters?
-
Struct layout. If
BUFF_SIZEis changed to1, what issizeof(MyString)on a 32-bit machine and on a 64-bit machine? Walk through how the compiler derives each number. -
Layout redesign.
BUFF_SIZE = 8but typical strings in your workload are 10–15 characters, so the inline buffer is almost never useful. How would you restructure the class so that one object can serve either role without paying for both at the same time?
A strong answer addresses each point with concrete reasoning. Where relevant, mention correctness issues you notice in the existing code.
Hints
Hint 1
For question 1, think about what extra work strncpy does beyond moving bytes, and what CPU feature lets memcpy skip that work entirely.
Hint 2
For question 4, start by writing out each member's size and its alignment requirement, then apply the two rules: each member starts at a multiple of its own alignment, and the total struct size rounds up to a multiple of the largest alignment.
Hint 3
For question 5, a small string and a heap-allocated string are mutually exclusive states — that is a strong hint that a union can overlap their storage, with a single flag byte distinguishing the two modes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Correctness issues worth flagging first
Before diving into the performance questions, a strong candidate points out that the class has bugs independent of any optimization work:
ptris uninitialized in the small-string branch. If a destructor callsfree(ptr), that is undefined behavior.- There is no destructor, copy constructor, or copy-assignment operator. The Rule of Three (or Five with move semantics) is violated: copying the object shallow-copies the raw pointer, and the second destructor double-frees it.
throw "not enough memory"throws aconst char*. The idiomatic choice isthrow std::bad_alloc{}.
1. Speeding up the inline copy
Replace strncpy with memcpy. The difference is what each function does with the length argument.
strncpy(buf, s, len) tests every byte for '\0' and zero-pads the remainder of the len-byte range. That is a data-dependent, byte-at-a-time loop that cannot be fully vectorized. memcpy(buf, s, len) trusts the caller-supplied length and moves bytes in the widest chunks the hardware supports. Compilers treat memcpy as a built-in and lower it to SSE/AVX instructions that move 16–32 bytes per instruction with no per-byte branching.
For a fixed small bound (here, under 128 bytes) there are additional tricks. For lengths in the range 8–16 you can issue two 8-byte loads/stores that overlap in the middle — at most two loads and two stores total, completely branch-free. If the source is another MyString buffer, you can copy the entire fixed-size block at once; a compile-time-constant memcpy length typically compiles to a handful of vector moves with no length-dependent loop.
Do not over-read arbitrary caller pointers. Reading past a page boundary can fault, so rely only on the length the caller supplied.
2. memcpy vs strncpy — behavioral differences
| Aspect | strncpy(buf, s, len) | memcpy(buf, s, len) |
|---|---|---|
| Embedded NUL bytes | Stops at the first '\0', zero-fills the rest | Copies all len bytes verbatim |
Source shorter than len | Safe: stops at the NUL | Over-reads into undefined memory — UB |
| NUL termination | Does not guarantee termination if no '\0' appears within len bytes | Never adds a terminator |
| Padding | Writes zeros beyond the actual string | Copies only what you asked for |
| Overlapping buffers | Undefined behavior | Undefined behavior (use memmove) |
Key pitfalls:
- With
strncpy, ifscontains an embedded NUL before positionlen, the storedlengthfield no longer matches the actual bytes. The object is in an inconsistent state. - With
memcpy, the caller must guarantee thatshas at leastlenreadable bytes. There is no guard. - In both cases the explicit
buf[len] = '\0'line is what makes the buffer safe to treat as a C string afterward — neither function provides that guarantee on its own.
When len == strlen(s) (no embedded NULs, exact length), both produce identical results. memcpy is strictly preferable in that case, and it is already what the large-string branch uses, so switching keeps the two branches consistent.
3. Why short-string comparison is much faster
The speed gap comes from memory hierarchy, not just byte count.
No pointer indirection. An inline string's characters live inside the object, in the same cache line as length. A heap string requires dereferencing ptr into a separate allocation — almost certainly a cache miss (~100 ns from DRAM versus ~1 ns from L1). For each operand compared, that is a full round trip to memory before the first character can be examined.
Cache residency. 256 bytes is four 64-byte cache lines and fits comfortably in L1. Long strings span many lines and saturate memory bandwidth; the comparison becomes I/O-bound rather than compute-bound.
Vectorized fixed-size compare. 256 bytes is 8 AVX2 or 16 SSE comparisons. A fixed upper bound allows full loop unrolling with no loop-carried branches and predictable control flow. Variable-length loops are harder to pipeline.
Branchless whole-buffer compare. If the unused tail bytes of the inline buffer are always zeroed out (a cheap invariant to maintain), two small strings can be compared as fixed-size blocks without consulting length at all — potentially a single memcmp of 16 bytes covering most common cases.
Cheap early exit. Comparing length first, then the first word, eliminates most unequal pairs before any character-by-character work begins. For SSO objects, both values are already in registers from the same cache line load.
4. sizeof(MyString) with BUFF_SIZE == 1
The compiler places each member at the nearest offset that is a multiple of its alignment, and pads the struct total up to a multiple of the largest member alignment.
32-bit (size_t and char* are 4 bytes, align 4):
| Offset | Member | Size |
|---|---|---|
| 0 | buf[1] | 1 |
| 1–3 | padding | 3 |
| 4 | length | 4 |
| 8 | ptr | 4 |
Total: 12 bytes.
64-bit (size_t and char* are 8 bytes, align 8):
| Offset | Member | Size |
|---|---|---|
| 0 | buf[1] | 1 |
| 1–7 | padding | 7 |
| 8 | length | 8 |
| 16 | ptr | 8 |
Total: 24 bytes.
Reordering members to put buf last does not help — the 1-byte tail still gets padded out to the same totals. The original BUFF_SIZE = 128 gives 136 bytes on 32-bit and 144 bytes on 64-bit, which is more than two cache lines per object and punishes dense containers significantly.
5. Redesigning for 10–15-character strings
The core insight: a string is either inline or heap-allocated, never both. That makes the two sets of fields candidates for a union, with a single flag bit distinguishing modes.
Here is a 16-byte layout for 64-bit, in the style of real SSO implementations:
class MyString {
union Rep {
// Small mode: up to 15 chars inline.
// small[15] holds (15 - size), so when the string is full
// that byte is 0 and doubles as the null terminator.
// The high bit of small[15] is always 0 in small mode.
char small[16];
// Large mode: pointer + 32-bit size + 32-bit capacity.
// The high bit of cap's most-significant byte is set to 1
// to signal heap mode (works on little-endian).
struct {
char* ptr;
uint32_t size;
uint32_t cap; // MSB = 1 means "heap"
} heap;
} rep;
bool is_small() const {
return !(reinterpret_cast<const uint8_t*>(&rep)[15] & 0x80);
}
};
What this buys you:
- Object shrinks from 144 bytes (original
BUFF_SIZE=128, 64-bit) to 16 bytes — four objects per cache line. - Strings up to 15 characters never allocate heap memory and never chase a pointer.
- The 10–15-character workload described in the question fits inline almost every time.
Trade-offs to acknowledge:
- Endianness. The bit trick depends on little-endian byte order. A big-endian variant needs different field placement.
- Capacity limit.
capis 32 bits, so max string length is ~2 GB. For most workloads that is fine; if you need full 64-bit lengths, use a 24-byte layout (up to 23 inline chars). - Mode branch. Every accessor checks
is_small(). The branch is highly predictable in practice because most objects stay in the same mode throughout their lifetime. - Copy and move complexity. Both operations must handle mode transitions (e.g., small → large on append), so the copy constructor and
operator=are more involved than with a flat layout.
Complexity summary
All operations (copy, compare) are O(n) in the string length. SSO reduces the constant: no heap allocation for short strings, no pointer dereference on access or comparison. Object size is fixed at sizeof(MyString); heap memory is only consumed for strings that exceed the inline capacity.