Unit Tests and Benchmarks in Rust

James Bowen
6 min readSep 7, 2020

For a couple months now, we’ve focused on some specific libraries you can use in Rust for web development. But we shouldn’t lose sight of some other core language skills and mechanics. Whenever you write code, you should be able to show first that it works, and second that it works efficiently. If you’re going to build a larger Rust app, you should also know a bit about unit testing and benchmarking. This week, we’ll take a couple simple sorting algorithms as our examples to learn these skills.

As always, you can take a look at the code for this article on our Github Repo for the series. You can find this week’s code specifically in sorters.rs! For a more basic introduction to Rust, be sure to check out our Rust Beginners Series!

Insertion Sort

We’ll start out this article by implementing insertion sort. This is one of the simpler sorting algorithms, which is rather inefficient. We’ll perform this sort “in place”. This means our function won’t return a value. Rather, we’ll pass a mutable reference to our vector so we can manipulate its items. To help out, we’ll also define a swap function to change two elements around that same reference:

pub fn swap(numbers: &mut Vec<i32>, i: usize, j: usize) {
let temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}

--

--