Editor’s note: This article was last updated 12 July 2022 to reflect updated survey data.
Rust and Python are both popular programming languages with overlapping use cases in software development and data science. Within the past few years, Rust’s adoption has grown significantly, leaving many wondering if it will eventually overtake Python as a top programing language.
In this article, we’ll compare the Rust and Python programming languages, discussing applicable use cases for each, reviewing each language’s pros and cons, and exploring why Rust has grown in popularity over the last few years. Let’s get started!
We’ll cover the following:
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 without garbage collection. Rust 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 in comparison to Python, Rust is still a young language, it has a steadily growing community. In fact, 86.98 percent of respondents to Stack Overflow’s 2021 Developer Survey named Rust their favorite programming language of 2021, as opposed to only 86.1 percent in 2020.
At first glance, Rust being statically and strongly typed may seem extreme. However, you’ll see in the long run that this helps to prevent unexpected code behavior.
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. If speed is paramount, you can use lower-level API calls, like CPython.
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.
Rust is used in systems development, operating systems, enterprise systems, microcontroller applications, embedded systems, file systems, browser components, simulation engines for virtual reality, and much more.
Rust is a go-to language when performance matters because it works well for processing large amounts data. It can handle CPU-intensive operations like executing algorithms, which is why Rust is more suitable than Python for systems 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:
Python can be used in many application domains, including web development, data science and analysis, AI and machine learning, and software development. In Summary, Python is:
You should use Python when:
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. Let’s consider some reasons why.
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
The code above will return the following 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())); }
We’ll get the following 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, meaning it took Python almost twice as long as Rust.
Rust has a very strict typing system, which provides developers with many benefits, like the following:
Security flaws in software often come from mismanaged memory or unforeseen mistakes in the codebase. This strictness in Rust helps us catch and prevent these kind of errors before they ever make it to the user.
Python, like 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, which ensures that references and pointers do not outlive the data they point to.
Python, like every other language, provides error checking and logging mechanisms. But, when it comes to letting the developer know what went wrong, there is some contrast between Rust and Python.
Take this typical example of a Python variable error:
apple = 15 print('The available apples are:', apple)
Below is Python’s 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
Let’s consider a similar example in Rust:
fn main() { let apple = 15; println!("The available apples are:", apple); }
Rust’s output is below:
println!("The available apples are:", aple); ^^^^ help: a local variable with a similar name exists: `apple`
In the code above, 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, the following:
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 out
, it cannot be changed. We’ll get the following error:
let grass = 13; | ----- | | | first assignment to `grass` | help: make this binding mutable: `mut grass`
The fixed error is shown below:
fn main() { let mut _grass: i32 = 13; _grass += 1; }
As you can see, now our code 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, however, Python does allow changes of this nature.
Rust is desirable due to its speed, guaranteed memory safety, 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 perform more in a shorter time without as many trade-offs. Rust helps achieve this without putting roadblocks in the developer’s way. As technology tries to push the boundary of what it can achieve, it also considers the safety and reliability of the system, which is the main ideology behind Rust.
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 you can’t use multiple CPU cores for intensive computing.
As mentioned earlier, 86.98 percent of respondents to Stack Overflow’s 2021 Developer Survey named Rust their favorite programming language of 2021:
Similarly, respondents to the 2020 HackerRank Developer Skills Report placed Rust in the top 10 programming languages they plan on learning next:
By contrast, the 2019 survey placed Rust toward the bottom of the list, suggesting that the community of Rust developers is growing rapidly:
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.
Rust: Pros | Rust: Cons | Python: Pros | Python: Cons |
---|---|---|---|
Fast | Substantial learning curve | Easy to use | Poor performance relative to lower-level languages |
Reduces memory-related errors | Large selection of libraries | ||
Growing selection of libraries and community support | Robust community |
Having evolved into a go-to programming language, Rust has seen an increase in its adoption. Although Python holds a firm place in the machine learning and 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 its strength in terms of application, performance, and speed, Rust isn’t just a programming language, it’s a way of thinking.
Debugging Rust applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking the 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 and mobile apps, recording literally everything that happens on your Rust application. 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 — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.
44 Replies to "Rust vs. Python: Could Rust replace Python?"
This article reminds me of a flat earther projecting that his “believe” finds widespread adoption within the next couple of years.
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.
Problems msec and microsec WRONG CALC. Only 2 times difference in speed.
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.
.oo86ms is 8.6us. twice as slow but not order of magnitudes slower as implied
> It took 0.0086ms to search
That is 8.6 microseconds, which is only twice as long as Rust’s 4.6 microseconds.
We are not responsible for the type of marijuana the author of this article consumes.
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.
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.
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.
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.
Python took 0.0086ms, which is 8.6us, that is still ~2 times slower, but not 2000 times
When benchmarking speed of Rust, use —release flag. cargo run —release. This make a huge diference.
Please verify the time comparison between rust and python execution… I think there is conflict between second and milliseconds
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.
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).
Rust is not going to replace python. Rust can be a good language. But it cant kill python
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…
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!
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.
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.
Oh! thanks Sam for pointing out that error. It is the unit that is wrong. I will correct it now.
Thanks for your suggestion @ Bijini
Cats could replace Bananas because cats are way cuter but both of them are yellow!
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.
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.
Next : Why microprocessor programming will take over scratch’s block programming? Will blow your mind!
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.
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.
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.
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.
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.
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.
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.
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.
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.
yeah, but he could also build the optimized non-debug version Rust binary
KISS is why I like python, ruby, and even squirrel. Those semicolons remind me of javascript hell.
It looks like the author fixed the runtime comparison error in their writing, but the code examples are still riddled with errors.
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
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.
I’d love to use Rust more, but the lack of dictionary support is painful. Yes, you can use hashmaps and jump through hoops to create objects that work a bit like proper dictionaries, but all that extra work means third party libraries (crates?) don’t use them for results in regex or sql queries. And if you’ve ever used languages with dictionary support for queries, you know its rough to go back.
Rust has 0 chance of replacing Python.
The actual competition for Rust isn’t Python, but C, C++, GO, etc…
People who use Python usually don’t care about absolute speed. Or rather they care more about development productivity over run speed. Unless your program has some massive computing tasks to do or has to run on severely constrained hardware run times like in the example are utterly irrelevant.
The power of Python is its readability and productivity – the run speed only needs to be ok. And it’s usually more than ok and can relatively easily be optimized by using a specialized module (which then is written in C or Rust) for the tiny parts that actually need to run extremely fast. And mostly you don’t even need that.
But if your function is not called a zillion times in a loop its run speed is usually of next to no importance.
Nobody will write the Linux kernel in Python. But most applications don’t need what Rust and C++ can do. And with Python you get quickly to running applications whose code is very easy to read and understand. *Much* easier than Rust.
That the speed part is not that relevant has already been proven by C or Cpp failing to eradicate Python. To the contrary actually.
Rust’s improved error messages are nice, but they are not an inherent part of the language. You could do the same in Python – or most other languages.
Compiler vs interpreter has different trade-offs. With compiled Rust you get speed which you often don’t need. With Python interpreter you get repl and introspection
Rust is a cool language. But I wouldn’t use it for the kind of programs I currently use Python for.
IPython as hell ,here but , ya I agree, Rust is a monster, i
t is highly valued in blockchain technology. Youngest startupss have already taken advantage of this.
Web3 is tomorrow …