Rust vs. Python: Why Rust could replace 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 could potentially overtake Python 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.

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 — .

Post a Comment

0 Comments