Most unique feature of rust which makes its memory safety guarantees, without any use of garbage collector.
Way to manage memory
Why should we manage memory?
Cannot optimize memory → Slow
Cannot predict memory collectors behavior → Unpredictable runtime
Invalid memory accessby programmer can be possible → Error prone
Memory writing is much slower → Slower write time
Ownership model : Slower than manual memory management
Stack | Heap |
---|---|
Store fixed sized data | Store dynamic sized data |
Fixed size | Dynamic in runtime |
Stack frames | Less organized |
Faster | Slower (Need time to looking for a place to store new data) |
Variable lives only inside of the stack frame |
fn main() {
let x = 5;
let y = x; //copy
let s1 = String::from("hello");
let s2 = s1; //move ownership
}
Make new heap allocation?
Expansive!
Especially when the data on the heap were large.
s2 = s1
could be very expensive in terms of runtime performance.
(allocation)
Make copy of pointers?