rust-lang / book

The Rust Programming Language

Home Page:https://doc.rust-lang.org/book/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

4.1 What is ownership — accuracy of 'The Stack and the Heap'

rillig opened this issue · comments

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:
    • stack heap
  • I have checked the latest main branch to see if this has already been fixed, in this file:
    • src/ch04-01-what-is-ownership.md

Description of the problem:

  • The text says that the stack can only take fixed-size objects.
  • The text says that accessing the heap memory is slower due to an extra pointer indirection.

I doubt these claims.

Regarding fixed-size objects: For example, in Go, objects are allocated on the stack or the heap depending on escape analysis. That is, if the object cannot be referenced after finishing the function call, it is allocated on the stack, no matter if it is fixed-size or variable-size.

Regarding memory access performance: As soon as an object is allocated (whether on the stack or on the heap), the runtime needs to keep a pointer to it, most probably in a CPU register, or in a local pointer variable. From that point on, accessing the object requires the same CPU instructions. And while access to the heap may indeed be slower due to uncached memory regions, this implementation and performance detail should not be in the introductory section about ownership.

Regarding analogies: The real-world examples (stack of plates, restaurant) felt like overexplaining to me. The analogies were not detailed enough to build a useful and trustworthy mental model from them. Instead of these examples, it would help to mention function calls and stack frames, and that both of them are nested structures that map naturally.

Suggested fix:

  • Remove the real-world examples from the text.
  • Double-check whether objects on the stack must really have a fixed size that is known at compile-time.
  • Double-check whether it makes sense to talk about memory access performance in this introduction.
  • If you decide to keep the restaurant scene, add a sentence about people leaving the restaurant, causing table fragmentation. Without this, there's nothing in the text that supports the claim that the heap be less organized.

Thanks for reporting. I had the some doubts and feelings when reading that section some months ago.