Rust – il linguaggio – 44

mwl_00_2-2

Continuo con Rust, oggi inizio la sezione Effective Rust [/usr/local/share/doc/rust/html/book/effective-rust.html], sono qui: /usr/local/share/doc/rust/html/book/the-stack-and-the-heap.html.

Lo stack e l’heap

Rust è un linguaggio di sistema, come il C. È quindi importante sapere come gestisce a memoria, con uno stack e un heap.

Non copio, tanto è tutto là, chiaro. Solo qualche cenno, altrimenti non riesco a fare il post 😉

Gestione della memoria

These two terms are about memory management. The stack and the heap are abstractions that help you determine when to allocate and deallocate memory.

Here’s a high-level comparison:

  • The stack is very fast, and is where memory is allocated in Rust by default. But the allocation is local to a function call, and is limited in size.
  • The heap, on the other hand, is slower, and is explicitly allocated by your program. But it’s effectively unlimited in size, and is globally accessible.

Lo stack

Let’s talk about this Rust program:

fn main() {
    let x = 42;
}

This program has one variable binding, x. This memory needs to be allocated from somewhere. Rust ‘stack allocates’ by default, which means that basic values ‘go on the stack’. What does that mean?

Well, when a function gets called, some memory gets allocated for all of its local variables and some other information. This is called a ‘stack frame’, and for the purpose of this tutorial, we’re going to ignore the extra information and just consider the local variables we’re allocating. So in this case, when main() is run, we’ll allocate a single 32-bit integer for our stack frame. This is automatically handled for you, as you can see; we didn’t have to write any special Rust code or anything.

When the function exits, its stack frame gets deallocated. This happens automatically as well.

Se poi il programma non è così semplice ci saranno altre variabili, p.es.:

fn foo() {
    let y = 5;
    let z = 100;
}

fn main() {
    let x = 42;
    foo();
}

This program has three variables total: two in foo(), one in main(). Just as before, when main() is called, a single integer is allocated for its stack frame. But before we can show what happens when foo() is called, we need to visualize what’s going on with memory. Your operating system presents a view of memory to your program that’s pretty simple: a huge list of addresses, from 0 to a large number, representing how much RAM your computer has.
Non continuo, le variabili vengono impilate (ehi! stack = pila), dai lo sappiamo (o è là). Salto pure tutto lo spiegone dell’heap [/usr/local/share/doc/rust/html/book/the-stack-and-the-heap.html#the-heap].
Anche perché non credo di aver davvero l’esigenza di gestire condizioni simili; anche con il C++ (il C non credo si usi normalmente) non è che ci si preoccupi più del necessario. Ma –aspetta che combinazione…

Cosa fanno gli altri linguaggi?

Most languages with a garbage collector heap-allocate by default. This means that every value is boxed. There are a number of reasons why this is done, but they’re out of scope for this tutorial. There are some possible optimizations that don’t make it true 100% of the time, too. Rather than relying on the stack and Drop to clean up memory, the garbage collector deals with the heap instead.

Cosa usare?

So if the stack is faster and easier to manage, why do we need the heap? A big reason is that Stack-allocation alone means you only have LIFO semantics for reclaiming storage. Heap-allocation is strictly more general, allowing storage to be taken from and returned to the pool in arbitrary order, but at a complexity cost.

Generally, you should prefer stack allocation, and so, Rust stack-allocates by default. The LIFO model of the stack is simpler, at a fundamental level. This has two big impacts: runtime efficiency and semantic impact.

Efficienza a runtime

Managing the memory for the stack is trivial: The machine just increments or decrements a single value, the so-called “stack pointer”. Managing memory for the heap is non-trivial: heap-allocated memory is freed at arbitrary points, and each block of heap-allocated memory can be of arbitrary size, the memory manager must generally work much harder to identify memory for reuse.

If you’d like to dive into this topic in greater detail, see Dynamic storage allocation: A survey and critical review, is a great introduction.

Impatto semantico

Stack-allocation impacts the Rust language itself, and thus the developer’s mental model. The LIFO semantics is what drives how the Rust language handles automatic memory management. Even the deallocation of a uniquely-owned heap-allocated box can be driven by the stack-based LIFO semantics, as discussed throughout this chapter. The flexibility (i.e. expressiveness) of non LIFO-semantics means that in general the compiler cannot automatically infer at compile-time where memory should be freed; it has to rely on dynamic protocols, potentially from outside the language itself, to drive deallocation (reference counting, as used by Rc<T> and Arc<T>, is one example of this).

When taken to the extreme, the increased expressive power of heap allocation comes at the cost of either significant runtime support (e.g. in the form of a garbage collector) or significant programmer effort (in the form of explicit memory management calls that require verification not provided by the Rust compiler).

Ho rimuginato sull’opportunità di pubblicare questo post; è fuori da quello che m’interessa, troppo da sistemista. Alla fine l’ho lasciato, ma se la sezione del manuale continua così cambio, salto, ometto, seleziono.
Vedrò. Prossimamente :mrgreen:

Posta un commento o usa questo indirizzo per il trackback.

Trackback

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...

Questo sito utilizza Akismet per ridurre lo spam. Scopri come vengono elaborati i dati derivati dai commenti.

%d blogger hanno fatto clic su Mi Piace per questo: