liveBook · Manning

Reallocation

As explained in Refactoring to Rust

Reallocation is the process of obtaining a larger memory area and moving existing data into it when the current storage is insufficient.

Reallocation copies existing data into a larger memory area when current storage cannot hold new data. Repeated string growth can trigger excessive allocations and copying. section 2.4.1

A growable Rust String manages reallocation through:

  • Length, which counts valid elements, and capacity, which counts elements the buffer can hold. section 2.4.1
  • Appending without reallocation while the new length remains within capacity. section 2.4.1
  • A new allocation and data copy when mutation exceeds capacity; the growth strategy is not guaranteed. section 2.4.1
  • Preallocation with String::with_capacity to reduce growth-related work when the required size is known. section 2.4.1
Listing 2.16 Creating a very large string one character at a time in Python
x = ""

for _ in range(0, 10_000_000):
  x += "."

print(len(x))

Compare repeated Python string concatenation, which creates many copied strings during a ten-million-character build. section 2.4.1

Listing 2.17 Creating a very large string one character at a time in Rust
fn main() {
  let mut x = String::new();  #1

  for _ in 0..10_000_000 {
      x.push('.');
  }

  println!("{}", x.len());
}

See Rust append characters to a growable String while hiding most buffer maintenance. section 2.4.1

Listing 2.18 Preallocating strings to aid performance
fn main() {
  let mut x = String::with_capacity(10_000_000);  #1

  for i in 0..10_000_000 {
    x.push('.');
  }

  println!("{}", x.len());
}

See known-size preallocation avoid capacity growth during repeated appends. section 2.4.1

How Refactoring to Rust covers it

How deep it goes
Explains length, capacity, overflow-triggered copying, and unspecified growth strategy, but does not specify an allocation algorithm.
Examples
Compares ten-million-character Python concatenation with Rust push loops and String::with_capacity.
What it assumes
Builds from basic string construction and introduces Rust String length and capacity through concrete mutation examples.
What you can do after
Apply Rust String mutation and preallocation to reduce unnecessary allocations during known or repeated growth.
How it connects
Connects allocation, capacity, mutable strings, heap allocation, and performance optimization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.