Igor Bubelov About Blog Photos

Rust

January 24, 2020

I used to code in Java but nowadays, I don’t use it often. Kotlin is my new language of choice, and I’m pretty excited about it. It’s more or less on par with C in terms of CPU efficiency, and it doesn’t consume as much RAM as one may think. It’s high level, strongly typed and resource efficient, is there a reason to use something else?

Rust is not as high level as Java or Kotlin, but it doesn’t need a virtual machine in order to run, which is important when you target resource-constrained hardware. A niche advantage? I agree, but that’s not all. The main advantage of Rust, in my amateur opinion, is code safety. It’s much harder to write unsafe code in Rust, and it’s where it really shines. Rust compiler is exceptionally smart, and it goes a long way to prevent you from introducing bugs in your code.

I worked in QA for a short time during my student years and here is a thing that stuck in my head since then: the earlier you can find a bug in your software, the less it will cost you. Bugs are expensive, and that’s one of the reasons I’m biased against languages that have little code quality checks. They may feel like freedom initially, but what they really do is stretching the feedback loop between introducing bugs and fixing them.

Another interesting thing about Rust is its concept of memory ownership. JVM uses garbage collector so Java/Kotlin programmers rarely think about memory or who can access or modify certain objects.

Here is a summary of Rust’s memory ownership system:

  • Each value in Rust has an owner.
  • Values can’t have more than one owner at a time.
  • Values get ‘dropped’ when their owners go out of scope.

That’s an interesting way to avoid having a garbage collector while not getting down to allocating and freeing up the memory, which is error-prone. Such a system allows us to write safe and performant code without a GC overhead, and it also guarantees that our threads won’t get halted while waiting for memory to be freed up.

Here is an interesting case study that compares Java and Rust in terms of memory consumption:

https://www.rust-lang.org/static/pdfs/Rust-Tilde-Whitepaper.pdf

It claims that the same code that consumed 5 GB of RAM inside JVM consumes just 50 MB after migrating to Rust. I very much doubt that, but I guess Rust can score up to 3x memory-efficiency advantage due to not using a garbage collector which might get memory-hungry under certain conditions.