David Adeneye Abiodun David Adeneye Abiodun is a software engineer and technical writer with a passion for making the web accessible for everyone.

Rust vs. Python: Why Rust is gaining in popularity

6 min read 1696

Rust vs. Python

In this guide, we’ll compare the Rust and Python programming languages. We’ll discuss applicable use cases for each, review the pros and cons of using Rust vs. Python, and explain why Rust is gaining in popularity.

We’ll cover the following:

What is Rust?

Rust is a multiparadigm language that empowers developers to build reliable and efficient software. Rust focuses on safety and performance, similar to C and C++, and is fast and memory-efficient with no garbage collections. It integrates with other languages and also runs on an embedded system.

Rust has excellent documentation, a friendly compiler with helpful error messages, and cutting-edge tooling, including an integrated package manager, build tools, smart multi-editor support with autocompletion and type inspections, an autoformatter, and more.

Rust was introduced in 2010 by Graydon Hoare of Mozilla Research. Although a young language compared to Python, Rust has a steadily growing community. In fact, 86 percent of respondents to Stack Overflow’s “2020 Developer Survey” named Rust their favorite programming language of 2020.

At first glance, Rust being statically and strongly typed may seem extreme. As you’ll see, this helps in the long run to prevent unexpected code behavior.

What is Python?

Python is a programming language designed to help developers work more efficiently and integrate systems more effectively. Like Rust, Python is multiparadigm and designed to be extensible. You can use lower-level API calls, such as CPython, if speed is paramount.

Python, which dates all the way back to 1991 when it was introduced by Guido van Rossum, is notable for its code readability, elimination of semicolons, and curly brackets.

Besides its extensible nature, Python is an interpreted language, which makes it slower than most compiled languages. As you might expect given its maturity, Python has a large ecosystem of libraries and a large, dedicated community.

When to use Rust

Rust is used in system development, operating systems, enterprise systems, microcontroller applications, embedded systems, file systems, browser components, simulation engines for virtual reality, and much more.

We made a custom demo for .
No really. Click here to check it out.

Rust is a go-to language when performance matters because it works well for processing large amounts data. It can handle CPU-intensive operations such as executing algorithms, which is why Rust more suitable than Python for system development.

Rust guarantees memory safety and lets you control thread behavior and how resources are allocated among threads. This enables you to build complex systems, which gives Rust an edge over Python.

To summarize, you should use Rust when:

  • Your project demands high performance
  • You are building complex systems
  • You value memory safety over simplicity

When to use Python

Python can be used in many application domains, ranging from web development, to data science and analysis, to AI and machine learning, to software development.

Python is widely used for machine learning, data science and AI because it is:

  • Simple and easy to code in
  • Flexible
  • Packed with an extensive selection of data-oriented packages and libraries
  • Supported by an excellent ecosystem of tools and libraries

You should use Python when:

  • You need a flexible language that supports web development, data science and analysis, and machine learning and AI
  • You value readability and simplicity
  • You need a language that is beginner-friendly
  • You prefer syntax simplicity and development speed over performance

Why Rust could replace Python

Given Rust’s rapidly growing popularity and wide range of use cases, it seems almost inevitable that it will overtake Python in the near future. Below are some reasons why.

Performance

One major reason why Rust is overtaking Python is performance. Because Rust is compiled directly into machine code, there is no virtual machine or interpreter sitting between your code and computer.

Another key advantage over Python is Rust’s thread and memory management. While Rust doesn’t have garbage collection like Python, the compiler in Rust enforces checks for invalid memory reference leaks and other hazardous or irregular behavior.

Compiled languages are generally faster than interpreted languages. But what puts Rust on a different level is that it’s nearly as fast as C and C++, but without the overhead.

Let’s see an example of an O(log n) program written in Python and calculate the time it takes to complete the task using an iterative approach:

import random
import datetime
def binary_searcher(search_key, arr):
    low = 0
    high = len(arr)-1
    while low <= high:
        mid = int(low + (high-low)//2)
        if search_key == arr[mid]:
            return True
        if search_key < arr[mid]:
            high = mid-1
        elif search_key > arr[mid]:
            low = mid+1
return False

Output:

> python -m binny.py
It took 8.6μs to search

Now let’s look at a timed O(log n) program written in Rust using an iterative approach:

>use rand::thread_rng;
use std::time::Instant;
use floating_duration::TimeFormat;

fn binary_searcher(search_key: i32, vec: &mut Vec<i32>) -> bool {
    let mut low: usize = 0;
    let mut high: usize = vec.len()-1;
    let mut _mid: usize = 0;
    while low <= high {
        _mid = low + (high-low)/2;
        if search_key == vec[_mid] {
            return true;
        }
        if search_key < vec[_mid] {
            high = _mid - 1;
        } else if search_key > vec[_mid] {
            low = _mid + 1;
        }
    }
    return false;
}

fn main() {
    let mut _rng = thread_rng();
    let mut int_vec = Vec::new();
    let max_num = 1000000;

    for num in 1..max_num {
        int_vec.push(num as i32);
    }
    let start = Instant::now();
    let _result = binary_searcher(384723, &mut int_vec);
    println!("It took: {} to search", TimeFormat(start.elapsed()));
   }

Output:

> cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.04s
Running target\debug\algo_rusty.exe
It took: 4.6μs to search
It took Rust 4.6 microseconds and Python 8.6 microseconds to perform similar operations on the same machine without any optimization techniques. That means it took Python almost twice as long as Rust.

Memory management

Python, as well as most modern programming languages, is designed to be memory-safe. Yet Rust gives Python a run for its money when it comes to memory-safety, even without garbage collection.

Rust embraced a unique way of ensuring memory safety that involves a system of ownership and a borrow checker. Rust’s borrow checker ensures that references and pointers do not outlive the data they point to.

Error checking and diagnosis

Python, like every other language, provides error checking and logging mechanisms. But there is some contrast between Rust and Python when it comes to letting the developer know what went wrong.

Take this typical example of a Python variable error:

apple = 15
print('The available apples are:', apple)

Python output:

Traceback (most recent call last):
    File "binny.py", line 2, in <module>
      print('The available apples are:', aple)
    NameError: name 'aple' is not defined

A similar example in Rust:

fn main() {
    let apple = 15;
     println!("The available apples are:", apple);
}

Rust ouput:

println!("The available apples are:", aple);
   ^^^^ help: a local variable with a similar name exists: `apple`

Here, Rust recommends possible variables that may have been what you wanted to type. Python only throws the error without giving suggestions on how to fix it.

Take, for example:

fn main() {
    let grass = 13;

    grass += 1;
}

This code throws an error because variables in Rust are immutable by default. Unless it has the keyword ou``t, it cannot be changed.

Error:

    let grass = 13;
      |         -----
      |         |
      |         first assignment to `grass`
      |         help: make this binding mutable: `mut grass`

Fixed error:

fn main() {
    let mut _grass: i32 = 13;

    _grass += 1;
}

As you can see, now it throws no errors. Besides this, Rust does not allow different data types to operate on each other unless they are converted to the same type.

Because of this behavior, maintaining a Rust codebase is generally easy. Rust does not allow changes unless specified. Python does allow changes of this nature.

Rust is desirable due to its speed, guaranteed memory safety, awesome reliability, consistency, and user-friendliness compared to most compiled languages. We’re getting to the point in programming where speed begins to become a no-brainer.

As technology evolves, it gets faster, trying to do more in a shorter time without as many trade-offs. Rust helps achieve this without getting in the developer’s way. As technology tries to push the boundary of what can be achieved, it also considers the safety and reliability of the system, which is the main ideology behind Rust.

Parallel computing

In addition to speed, Python also has limitations when it comes to parallel computing.

Python uses Global Interpreter Lock (GIL), which encourages only a single thread to execute at the same time to boost the performance of single threads. This process is a hindrance because it means you can’t use multiple CPU cores for intensive computing.

Community

As mentioned earlier, 86 percent of respondents to Stack Overflow’s “2020 Developer Survey” named Rust their favorite programming language of 2020.

Rust vs. Python: Stack Overflow Survey

Similarly, respondents to the “2020 HackerRank Developer Skills Report” placed Rust in the top 10 programming languages they plan on learning next:

Rust vs. Python: HackerRank Survey 2020

By contrast, the 2019 survey placed Rust toward the bottom of the list, suggesting that the community of Rust developers is growing rapidly.

Rust vs. Python: HackerRank Survey 2019

As this data shows, Rust is becoming part of the mainstream developer community. Many large companies use Rust and some developers even use it to build libraries that other programming languages use. Notable Rust users include Mozilla, Dropbox, Atlassian, npm, and Cloudflare, to name just a few.

Amazon Web Service has also adopted Rust for performance-sensitive components in Lambda, EC2, and S3. In 2019, AWS announced its sponsorship of the Rust project and has since provided Rust with the AWS SDK.

Companies are increasingly replacing slower programming languages with more efficient ones like Rust. No other language nails the tradeoff between simplicity and speed like Rust.

Conclusion

Rust has evolved into a go-to programming language has seen an increase in its adoption as a result. Although Python holds a firm place in the machine learning/data science community, Rust is likely to be used in the future as a more efficient backend for Python libraries.

Rust has huge potential to replace Python. With the current trend as a go-to programming language of choice in terms of application, performance, and speed, Rust isn’t just a programming language, it’s a way of thinking.

LogRocket: Full visibility into production Rust apps

Debugging Rust applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking performance of your Rust apps, automatically surfacing errors, and tracking slow network requests and load time, try LogRocket.

LogRocket is like a DVR for web apps, recording literally everything that happens on your Rust app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.

Modernize how you debug your Rust apps — .

David Adeneye Abiodun David Adeneye Abiodun is a software engineer and technical writer with a passion for making the web accessible for everyone.

40 Replies to “Rust vs. Python: Why Rust is gaining in popularity”

  1. This article reminds me of a flat earther projecting that his “believe” finds widespread adoption within the next couple of years.

  2. First of all 0.0086ms is 0.000086s.
    Secondly, use list comprehension, numpy or Numba, they exist in Python for that reason.
    If you do that you will get a performance close to Rust performance.

    Finally, I like Rust, but it has nothing to do with Python use cases. If you work on big data, pyspark, computer visions projects, you know that comparison between Rust and Python is absolutely none scenes.

  3. This article must be a joke. Even the most amateur developer knows that the two languages have completely different domains that do not intersect. Rust chances to replace Python are no more than C++ replacing VBA. Python is about simplicity and high level tasks. Rust is a modern take on C++. I fail to understand how a comparison can be drawn on the first place.

  4. > It took 0.0086ms to search

    That is 8.6 microseconds, which is only twice as long as Rust’s 4.6 microseconds.

  5. Rust is no doubt accelerating in popularity but I doubt it will ever pass python. Primarily because of options simplicity to learn. In an ideal world everyone would learn rust instead of python and we would have faster and more reliable code bases.

  6. For Python, result ils 0.0086ms so that to say 0.0000086 s !
    Rust result is 0,0000046 s.
    On this test, Rust is twice faster. And if you suppress Python module loading time, Python is as faster as Rust…..

    For performance comparison, you must try differents tests with differents cyclomatic complexity, and different compilation options. In Python you need to perform a lot of tests or suppress modules loading time. Or don’t speak about performance, but end to end time.

  7. What… No it could not. You don’t use Rust and Python in the same situations and for the same purposes and you know this perfectly well, you even explain it yourself in your post.

  8. There’s something wrong with your benchmarks.

    “It took Rust 0.0000046 seconds to complete the task compared to 0.0086 seconds for Python.
    It is evident that Rust outperforms Python.”

    The python output states: “It took 0.0086ms to search”. That’s 8.6 microseconds.

    I’d also suggest running something that takes at least a few seconds to complete. As too many factors could easily eschew the results of such a miniscule time frame.

  9. Please verify the time comparison between rust and python execution… I think there is conflict between second and milliseconds

  10. There is a mistake, in your Screenshot the python O(logn) Programm took 0,0086milliseconds but later in the article you were talking about 0,0086 seconds. So actually the rust program was just twice as fast.

  11. There is no logical way Rust could or would replace Python. They’re completely different languages with different purposes.

    Python is a high level language that is designed to be incredibly readable. It’s interpreted, which makes it usable (and extremely powerful) as a scripting language, something Rust can’t do. Its popularity in AI and Data Science is driven by how easy it is for someone who isn’t a full-time developer to write and understand, while the underlying libraries (tensorflow, numpy, etc) are written in C to give the performance of a native language with the usability of Python.

    Rust is designed to be a high performance, memory safe language without garbage collection for writing system code and applications. You could use Rust for Data Science, but the learning curve would be much steeper and if all you’re doing is creating bindings to existing frameworks, what’s the point?

    It’s nonsensical to consider replacing Python with Rust. A Python interpreter written in Rust however, is a lot more interesting to think about (e.g. RustPython).

  12. When you compare speed for O(logn) programs in Python an Rust I think you did a mistake in conclusion. In Python the script need 0.0086 ms to complete.”ms” stands for millisecond not second as you said in your conclusion. So the Python script take 8.6 micro seconds to complete and the Rust one 4.6 micro seconds. So yes Rust was quicker but not as you stated in your conclusion…

  13. Hi David, really interesting article! 🙂

    I think there is a little mistake in your first benchmark.
    Console output:
    Python: 0.0086 ms
    Rust: 4.6 us

    So basically it’s 8.6 us VS. 4.6 us (~2x speed-up), not 8.6 ms VS. 4.6us (~2000x speed-up). So either the units are wrong in the benchmark or in the text.

    Would be interested in the actual speed-up, though!

  14. Check your units on performance. 0.0086 milliseconds is 8.6 microseconds, so your example shows a 2x performance gain in Rust, not the orders of magnitude you’ve shown in your analysis.

  15. No, just read your examples, the Python array search is indeed slower but that syntactic mess is exactly why I chose Python. Your article has confirmed my choice, thanks.

  16. Oh! thanks Sam for pointing out that error. It is the unit that is wrong. I will correct it now.

  17. There is a mistake in error checking paragraph. Python code is written without any mistakes and it’s output should be clear. Also, presented traceback output clearly indicates the error, giving its name + description, what a developer needs. I would recommend author to read Python official docs and practice more if he wants to become a better programmer, because all these indicate that he is a complete idiot in this particular language.

  18. Sorry to say but these benchmarks are meaningless.

    1. Rust benchmark is a dev build. Use –release: it’s a huge amount faster. Dev is unoptimised.
    2. You can’t measure a single shot, especially with python
    3. Millisecond and microsecond confusion
    4. Have to use a variety of inputs and many thousands of samples: find different numbers each time in the search.
    5. System timer can be quite inaccurate (pretty sure that’s what datetime in python means)

    Benchmarking is hard, and I hardly ever see it done correctly. Experiments are hard to get valid results out of, in general.

    The best approach is to use some proper tools to do this stuff, and follow the advice carefully. Criterion for Rust is good. I forget what the Python options are, but they’re there too. They address the sampling issues, timer accuracy, etc.

  19. You write about the Olog(n) program example: “It took Rust 0.0000046 seconds to complete the task compared to 0.0086 seconds for Python”, but the code snippet for Python returned “It took 0.0086ms to search”. So the execution speed difference seems a factor 2 different, not a factor 2000. That is an important difference if your main argument boils down to execution speed of Rust VS Python.

  20. Surely you must be joking? You can replace Rust with Java, or Go, or even C++, and the arguments would still hold; and yet none of those languages have replaced Python and so neither will Rust, just as none of those languages have replaced, or will replace sh/bash, for similar reasons.

    Also, you may want to measure the wall clock with time for both Python and `cargo run` — it could well turn out that Python was overall faster since it didn’t have to spend time on optimization.

  21. If I read the graphs correctly, it looks like Rust has actually slipped in popularity by a couple percentage points as the language programmers want to learn next from 2019 to 2020. You need to compare the lengths of the bars, not the order it appears in a unsorted list. And ditto on the performance metrics snafu. This article presents evidence that contradicts its claims leaving any sharp reader with the sense that the author shouldn’t be a writer.

  22. It is possible that Python is replaced by another interpreted language, but it is silly to say a compiled language replaces Python. Every one know that compiled languages run faster than interpreted ones, but there still exists a lot of interpreted languages next to compiled one without being replaced. There are cases that runtime speed is not so important as development time and people have to invent interpreter languages for it.

  23. Same. Also, there is a bug in Python example, where author tries to throw an variable error ‘aple’, but the code has everything spelled right, so there should be no error in console output.

  24. Wow, this article has already been ripped to shreds, but I want to add one more thing. As someone else pointed out, the benchmark test is completely meaningless since it’s such a small sample. However, even if it’s accurate and if Rust is two times faster than Python when accessing some memory (which probably isn’t the case), the likelihood of that making a measurable difference in a real application is slim. With the exception of compute-heavy applications, the biggest bottleneck is likely to be IO. Having the fastest sorting algorithm in the world doesn’t matter when your code is twiddling its thumbs waiting to load a file or get the results of a database query.

    Why must we endure so many “I like this more so I’m going to tell the internet it’s better and will win” articles? Please stop.

  25. The performance test is just completely wrong. The binary search has complexity O(log n), but the initialization of the array is O(n), so you are basically measuring array initialization time only.

    Moreover, the published python code does not seem to be complete.

  26. Python doesn’t do garbage collection. CPython (aka python, the default implementation) uses reference counting, which is why it needs the Global Interpreter Lock.

    IronPython and Jython (.NET and Java based Python respectively) use garbage collection.

  27. Finally someone who makes sense. Obviously, comparing these two is idiotic. Nobody will use Rust instead of Python. They are completely unrelated in their use. Python is slow but easy to use, Rust seems a bit faster, although this here example script is probably irrelevant, cuz being twice faster than Python still means horribly slow.. but Rust is ugh, hard to read, hard to write. It’s like comparing apples and airplanes.

  28. KISS is why I like python, ruby, and even squirrel. Those semicolons remind me of javascript hell.

  29. It looks like the author fixed the runtime comparison error in their writing, but the code examples are still riddled with errors.

  30. Python is as simple as a programming language can get. On the other hand Rust is low level, systems language. I used it a bit and it takes time to get a handle on. I don’t see what simplicity you’re talking about

  31. CPython has had garbage collection for several years. It still has reference counting, which can be used to delay (or even eliminate) garbage collection.
    It still has the Global Interpreter Lock, for reasons that have nothing to do with garbage collection.

Leave a Reply