Rust: Reassign vs Mutate

Rust: Reassign vs Mutate

An implementation, memory, and performance comparison between reassignment and mutation in Rust

Image for post

Knowing when to use mutations versus reassignments is a common decision in many programming languages and in a memory-safe language like Rust, they are an essential question. As Rust is dominated by knowing how to borrow effectively, we can ease our way into its rules by looking at the Rust language through the lens of reassignment versus direct mutation.

Note: After this, read up on Ownership and how it relates to borrowing, slices, and memory management of your Rust variables. You probably already know some of this if you are using Rust, but it does not hurt to read through this section.

In a lot of cases, Rustaceans refer to the performance impact of using something like [Clone](https://doc.rust-lang.org/std/clone/trait.Clone.html) or [Copy](https://doc.rust-lang.org/std/marker/trait.Copy.html) traits in Rust, which allow duplication of a struct into a brand-new variable binding.

Below, we will look at the memory impact of using mutable object references, copied objects, and cloned objects alongside code examples (full source code here). Benchmarks at the end.


Simple Example: Bicycle — Clone vs Mutate

Image for post

Photo by Kiwihug on Unsplash

To begin, we have a Bicycle module, which is a considerably simple struct with a couple of methods: a constructor and a mutator for a Bicycle instance:

#[derive(Copy, Clone)]
    pub struct Bicycle {
        speed: u32,
    }

    impl Bicycle {
        pub fn new(speed: u32) -> Bicycle {
            Bicycle { speed: speed }
        }

        pub fn accelerate(&mut self) {
            println!("current speed: {}", self.speed);
            self.speed += 1;
        }
    }

Internally, the accelerate method mutates the speed field each time it is called.

Also, take note of the #[derive(Copy, Clone)] attribute which allows us to duplicate the struct easily.

Using this module, we can then create two different examples that demonstrate how a given bicycle instance can be modified.

Clone Bicycle

In this first example, the code clones the bicycle:

mod bicycle;

    const NUM_BIKES: u32 = 100_000;
    const TOTAL_EPOCHS: u64 = 5;

    use bicycle::Bicycle;

    fn main() {
        println!(
            "=== clone_bikes - {} v{} ====",
            env!("CARGO_PKG_DESCRIPTION"),
            env!("CARGO_PKG_VERSION")
        );
        let mut bikes: Vec<Bicycle> = Vec::new();

        for i in 0..NUM_BIKES {
            bikes.push(Bicycle::new(i));
        }

        println!("Lets reassign!");

        for _i in 0..TOTAL_EPOCHS {
            for j in 0..bikes.len() {
                let mut bike = bikes[j].clone();
                bike.accelerate();
                bikes[j] = bike;
            }
        }

        println!("Done!");
    }

rust code technology programming benchmark

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How Benchmarking Your Code Will Improve Your Ruby Skills

Learning to code is a path full of struggles, and learning Ruby isn't the exception. But you'll agree with me, that practice is the best way to learn and develop your skills.

13 Free/Low-Cost Sites to Supercharge Your Programming Self-Education

Although we still talk about programming as a standalone career, the dominance of technology in our lives makes it clear that coding is much more than a career path. In my opinion, computer science is more than a college major or a high-paid job; it’s a skill, essential for thriving in a modern-day economy. Whether you work in healthcare, marketing, business, or other fields, you will see more coding and have to deal with a growing number of technologies throughout your entire life.

How to Structure Your Programming Code

I remember my first fumble with basic on my ZX Spectrum computer back in the 1980s, ploughing through pages of basic commands and example code without any real idea of how I could write programs myself

What Is Code Golfing And Biggest Such Tournaments

Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Playing code golf is known as "golf scripting". Code golf challenges and tournaments may also be named with the ... Some code golf questions, such as those posed on general programming ...

Coding 101: Programming Language Building Blocks

This article will introduce the concepts and topics common to all programming languages, that beginners and experts must know!