Not Just for Systems

I've been using and enjoying a lot of lately. My most recent foray into Rust Lang was brought on by a challenge started among some friends to write a program that could find the longest word in a text as fast as possible. My initial joking attempt was done in BASH and it was mildly successful, but slower than pretty much everything other than Python and Node.JS. So I wrote a Rust version.

Rust is fast! Fast enough to propel me into a race for the fastest with a PHD candidate who wrote his implementation in C++. In fact, in the multithreaded category Rust is the clear victor! And that is the code that made me stop and consider that Rust is not just a systems language. I've pulled out the code relevant to my concurrent method and I think it illustrates nicely what I am getting at:

extern crate rayon;

use std::env;
use std::fs;
use std::time;
use rayon::prelude::*;

fn main() {
    let filename = env::args().nth(1).unwrap();
    let file: std::string::String = fs::read_to_string(filename).expect("");

    let start = time::Instant::now();

    let longest = file.par_split_whitespace().max_by_key(|word| word.len()).unwrap();

    let elapsed = start.elapsed();
    let seconds = ((elapsed.as_secs() as f64) + (elapsed.subsec_nanos() as f64 / 1_000_000_000.0)) * 1000.0;

    println!("Longest word is '{}' with a length of {} characters.", longest, longest.len());
    println!("It took {} milliseconds to find this word.", seconds);

We're looking at 34 LOC, and really not even that much when you take out the timing. The key line to this code is:

let longest = file.par_split_whitespace().max_by_key(|word| word.len()).unwrap();

Such a very "scripty" and "pythonic" piece of Rust code! Also, it's vastly faster than the Pythonic solutions created for the challenge. There isn't a concurrent Python solution submitted yet, but this code in a single thread finds the longest word in our test corpus in just over 1000ms. The python code takes just under 7000ms. The concurrent version (shown above) gets its answer in 197ms, faster than the next fastest, C#, by over 500ms!

So yes, Rust is a systems language. But Rust is so much more than that too!