String Internals, Move Costs, and Threads vs Async Tasks
StringsModel answerLast updated
Describe how a string is laid out in memory, what copying and moving really cost, what a Rust move does, and how OS threads differ from async coroutines.
This is a fundamentals discussion. Answer each part concretely, using memory layouts, byte counts and big-O costs where they help.
- What is a string? Explain how mainstream languages represent one (for example C, C++, Rust, Java, Python), and what separates mutable from immutable designs.
- Layout. Which fields would a typical owning, growable string struct hold? Describe how you would implement one yourself, including growth policy, copy behavior and cleanup.
- Copy cost. What is the time complexity of copying a string? Do the answer for several designs: deep copy, short-string optimization, immutable or reference-counted strings, and copy-on-write.
- Efficient moves. What is a move, and what can you do so that moves stay cheap in practice?
- Rust specifically. A colleague says: "In Rust, moving a
Stringjust changes the reference." Is that right? Describe what really happens to the value, the heap buffer, and the source variable. - Threads vs. async coroutines. Compare them on scheduling, stack usage, switch cost, scalability, parallelism, suitable workloads and typical failure modes.
A strong answer is structured, gives numbers (such as struct size on a 64-bit machine), and flags common pitfalls.
Hints
Hint 1
Think about what an owning string must track in order to find its data, know where it ends, and append without reallocating every time. Count the machine words.
Hint 2
Separate what is copied (the small inline struct) from what is not touched (the heap buffer). Then ask what the compiler does with the source variable afterwards, and whether a runtime reset is needed.
Hint 3
For threads vs. coroutines, distinguish concurrency from parallelism, then compare who decides when to switch (kernel vs. the program itself) and what happens when one task blocks.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. What is a string?
A string is a sequence of characters stored as bytes in some encoding, plus enough metadata to know where it ends. Representations differ:
- C: a
char*to a null-terminated array. Length is O(n) because you scan for\0; embedded zero bytes are impossible; overflows are a classic bug. - C++
std::string: a mutable, owning buffer with an explicit length. - Rust:
Stringis an owned, growable buffer guaranteed to be valid UTF-8.&stris a borrowed fat pointer(ptr, len). - Java / Python: immutable heap objects. Java uses a
byte[]plus an encoding flag and a cached hash. CPython picks 1, 2 or 4 bytes per code point depending on the widest character.
Immutability makes strings safe to share, hash and intern, at the price of allocating a new string for every "modification".
2. Fields and a DIY implementation
An owning growable string is typically three words (24 bytes on 64-bit):
| Field | Meaning |
|---|---|
ptr | pointer to the heap buffer |
len | bytes in use |
cap | bytes allocated, cap >= len |
Rust's String wraps a Vec<u8> with exactly this shape. C++ implementations add a small-string optimization (SSO): short strings live inside the struct itself, so there is no allocation (roughly 15 chars in libstdc++, 22 in libc++).
To build one:
- Store
ptr/len/cap. - Grow geometrically (x1.5 or x2) on append, giving amortized O(1) appends.
- Define a deep-copy constructor/assignment explicitly.
- Define a move constructor/assignment that steals the buffer.
- Free the buffer exactly once in the destructor.
- Optionally add SSO, a cached hash and encoding validation.
Sketch (C++-style, in Python-like pseudocode):
class MyString:
def __init__(self, data=b""):
self.cap = max(len(data), 8)
self.buf = bytearray(self.cap)
self.buf[:len(data)] = data
self.len = len(data)
def append(self, data):
need = self.len + len(data)
if need > self.cap: # geometric growth
self.cap = max(need, self.cap * 2)
nb = bytearray(self.cap)
nb[:self.len] = self.buf[:self.len] # O(n), amortized away
self.buf = nb
self.buf[self.len:need] = data
self.len = need
def copy(self): # deep copy, O(n)
return MyString(bytes(self.buf[:self.len]))
def move(self): # O(1): steal, reset source
new = MyString.__new__(MyString)
new.buf, new.len, new.cap = self.buf, self.len, self.cap
self.buf, self.len, self.cap = bytearray(0), 0, 0
return new
3. Cost of copying
- Deep copy: O(n): one allocation plus a
memcpyoflenbytes. - SSO string: effectively O(1), bounded by about 15-22 bytes.
- Immutable / refcounted: O(1); copy a pointer and bump a count (Java and Python assignment).
- Copy-on-write: O(1) to copy, but the first write pays O(n). C++11 effectively ruled out COW for
std::stringbecause of thread-safety and iterator-invalidation problems.
4. Making moves efficient
A move transfers ownership of the buffer: copy the three words, then leave the source empty (ptr = null, len = cap = 0) so its destructor does nothing. This is O(1) regardless of length.
Practical tips:
- Mark move constructor/assignment
noexceptin C++. Otherwisestd::vectorcopies instead of moving on reallocation to keep its strong exception guarantee. - Rely on copy elision (RVO/NRVO): returning by value often constructs directly in the caller's slot, so no move occurs.
- Use
std::moveon the last use of a value; take sink parameters by value and move them into place. - Keep the inline part small. Large inline arrays are expensive to move; put them behind a
Box/unique_ptr. reserveup front to avoid repeated reallocations, each of which moves or copies elements.
5. Does a Rust move only modify the reference?
No. There is no reference involved.
- A move is a bitwise copy of the value's inline bytes. For
String, that is the 24-byte{ptr, cap, len}. The heap buffer is untouched. - The source is not zeroed at runtime. The compiler statically marks it as moved-from: later use is a compile error and its destructor is skipped. For conditional moves the compiler adds hidden drop flags.
- The optimizer often removes the
memcpyaltogether by building the value in place.
Consequences:
- Moving a
[u8; 1_000_000]copies 1 MB, so box large values. - Rust has no user-defined move constructors; moves are always plain memcpys. That is why self-referential types need
Pin: a memcpy would leave internal pointers dangling. Copytypes are also memcpy'd, but the source remains usable.
6. Threads vs. async coroutines
| OS thread | Async coroutine | |
|---|---|---|
| Scheduling | Preemptive, by the kernel | Cooperative; yields at await |
| Stack | Own stack (often 8 MB reserved on Linux; 2 MB for Rust std::thread) | Stackless state machine in Rust/Python/JS; size equals live state across awaits |
| Switch cost | ~1-5 us | tens to hundreds of ns |
| Scale | thousands | hundreds of thousands to millions |
| Parallelism | true multi-core | concurrency on one thread unless the runtime is multi-threaded (e.g. work stealing) |
| Best for | CPU-bound work, blocking APIs | I/O-bound work with many waits |
| Failure mode | data races, lock contention | one blocking call or CPU loop stalls the executor |
Key points:
- Async gives concurrency (many tasks in flight); threads give parallelism (tasks running simultaneously).
- In CPython the GIL limits thread parallelism for CPU work (until free-threaded builds), so use processes.
- Offload blocking calls in async code with
spawn_blockingorrun_in_executor.
Common mistakes and edge cases
- Saying a Rust move "updates a pointer" or "zeros the source".
- Treating
lenas a character count; it is bytes. Indexing UTF-8 by character is O(n), which is why Rust forbidss[i]. - Forgetting self-assignment safety (
s = s,s = std::move(s)). - Using a moved-from C++ object as if it had a known value; it is valid but unspecified and must stay safe to destroy.
- Building strings with
s += xin a loop for immutable strings (O(n^2)); use a builder orjoin. - Calling blocking functions inside async tasks.