Skip to main content

Comparing speed of some fast languages

To get more familiar with Rust, I’ve lately been revisting last year’s Advent of Code problems, which I did in Go last December. My Go solution solution for Day 5 uses brute-force and is not very clever, but runs fast enough in Go (under 6 minutes). The Rust equivalent runs in 1/3 less time, and I was wondering how other languages would fare. The results might surprise you.

I ended up writing the solution in Rust, Zig, and C, in addition to the original Go solution.

The problem (at least my naive solution) is good for a language benchmark because it involves lots of repeated transformations through a series of logic steps, with math, logic, and branching/looping. It took 5:40 minutes in Go, and Rust brought that down to 3:45 (when compiled with the –release flag). The results for the four languages are interesting (times in minutes):

Times

Go takes 50% longer than Rust, better than I expected. As you’d expect, C is faster than Rust, and at 2:40 by quite a margin (compiled using gcc with -O3 flag for optimizations, and clang did even better at 2:21). And the big surprise was Zig, which ran in 1:51, using its ReleaseFast optimization flag(i.e., zig build -Doptimize=ReleaseFast).

The cost of speed: lines of code?

Another comparison is lines of code. You’d expect Rust to require fewer lines of code because of its expressive syntax, with function chaining, functional programming (map, filter, etc.), macros and the like. This is indeed the case. C and Zig are lower level, and require more lines (and programming time) to produce results:

Lines of code

However, you can see from a scatter plot of these two how Zig blows the other languages out of the water from an execution time point of view, while requiring almost 20% fewer lines than C, and roughly the same as Go:

Lines vs time

Note that these line counts exclude comments and blank lines.