Using Immutability over Mutability
Context
During software development, a key decision is choosing between immutable and mutable variables. Immutable variables, once created, remain unchanged, while mutable ones can be altered post-creation. OOP languages like Java and C# default to mutable variables, whereas functional languages like Haskell and Scala favor immutability.
Opinion
Preferring immutability often yields more predictable and maintainable code by minimizing unexpected side effects and simplifying debugging.
How to Implement
struct Point {
x: i32,
y: i32,
}
impl Point {
// Create a new Point with updated x value, without mutating the original
fn set_x(&self, new_x: i32) -> Point {
Point {
x: new_x,
y: self.y,
}
}
fn set_y(&self, new_y: i32) -> Point {
Point {
x: self.x,
y: new_y,
}
}
}
Performance Check
use std::time::Instant;
fn mutable_simulation() {
let start = Instant::now();
let mut user = User { name: String::from("John") };
for i in 0..1_000_000 {
if i % 2 == 0 {
user.name = String::from("John");
} else {
user.name = String::from("Jane");
}
}
let duration = start.elapsed();
println!("Time elapsed in mutable operation is: {:?}", duration);
}
fn immutable_simulation() {
let start = Instant::now();
let mut user = User { name: String::from("John") };
for i in 0..1_000_000 {
if i % 2 == 0 {
user = User { name: String::from("John") };
} else {
user = User { name: String::from("Jane") };
}
}
let duration = start.elapsed();
println!("Time elapsed in immutable operation is: {:?}", duration);
}
#[derive(Debug)]
struct User {
name: String,
}
fn main() {
mutable_simulation();
immutable_simulation();
}
/\*\*
- Time elapsed in mutable operation is: 150.991897ms
- Time elapsed in immutable operation is: 137.375402ms
\*/