-
No Crash in Rust due to:
1. Ownership,
2. Borrowing,
3. No Manual Memory management
Faster wrt C++: 4. Aggressive Complier Optimizations, 5. Lower Runtime overheads wrt C++
Smaller Binary wrt C++: 6. No RTTI in Rust
Rust Over C++
| C++ | Rust | |
|---|---|---|
| Ownership | No concept of ownership | Yes |
| Reference(or Borrowing) | Unsafe (Lead to crashes) | Safe (No crash) |
1. Ownership (avoid crash in Rust)
Ownership?
- Defines how memory is managed safely(without need of garbage collector) by Rust program.
- Every Variable/data have single owner at a time. When the owner goes out of scope, Rust automatically deallocates the memory.
- Ownership rules are checked at compile time. Ownership applies to memory allocated on heap(dynamically),
Eg: String(), vector ie those are moved. For variable allocated on Stack (Eg: int, float) variable is copied.
In Rust, raw pointers (*const T and *mut T) don't embody ownership semantics directly.
However, smart pointers like Box <T>, Rc<T>, and Arc<T> do.
- Box<T>: It represents ownership of a heap-allocated value.
- Rc<T>: It provides reference counting and allows multiple ownership.
- Arc<T>: It's like Rc<T>, but with atomic reference counting, suitable for concurrent access.
| C++ (Crash in C++) | Rust (No null pointer Exception(Crash) in Rust) |
unique_ptr
|
|
3. No Manual Memory management (avoid crash in Rust)
- Though C++ provides smart pointers, still someone can leak using C++98 new() and delete()
- Rust's ownership and borrowing rules ensure memory safety without the need for manual memory management.
C++
|
Rust
|
4. Aggressive Compiler Optimization (make Rust fast)
Inlining
- Rust's Compiler(LLVM) optimizes code more aggressivly wrt C++ compiler
& this is because of ownership rules, LLVM can make assumptions.
- LLVM is more aggressive about inlining functions, especially for small functions.
Inlining avoids function call overhead and makes it fast.
5. Lower Runtime overheads wrt C++ (make Rust fast)
- 5.1
C++ Stack Unwinding causes runtime slowness
C++ (On Exception Stack Unwinding happens)
|
Rust (Result and Option types for error handling, which are handled through pattern matching rather than exceptions)
|
5.2 C++ Runtime Type Information (RTTI) increases binary size and runtime overhead
- Rust's type system(based on traits and enums), enables polymorphic behavior and dynamic dispatch without the need for RTTI.
C++
|
Rust Box
|