Rust and python: why rust can replace Python

Time:2021-4-18

In this guide, we compare the rust and python programming languages. We will discuss the applicable use cases in each case, review the advantages and disadvantages of using rust and python, and explain why rust might replace python.

I will introduce the following:

  • What is rust?
  • What is Python?
  • When to use rust
  • When to use Python
  • Why can rust replace Python

What is rust?

RustIs a multi paradigm language that enables developers to build reliable and efficient software. Rust focuses on security and performance, similar to C and C + +, with high speed, high memory efficiency and no garbage collection. It can be integrated with other languages and run on embedded system.

Rust ownsExcellent documentation, friendly compiler and useful error information, as well as advanced tools, including integrated package manager, build tools, intelligent multi editor support, automatic completion and type checking, automatic formatting, etc.

Rust was launched in 2010 by Graydon Hoare of Mozilla research. Although rust is a young language compared to python, its community is growing steadily. In fact, in stack overflow’s 2020 developer survey, 86% of respondents rated rust their favorite programming language in 2020.

At first glance, static and strongly typed rust may seem extreme. As you can see, this helps prevent unexpected code behavior in the long run.

What is Python?

PythonIs a programming language designed to help developers work more efficiently and integrate systems more effectively. Like rust, Python is multi paradigm and designed to be extensible. If speed is the most important, you can use low-level API calls, such asCPython

Python’s history can be traced back to 1991 when Guido van Rossum introduced python, which is famous for its code readability, elimination of semicolons and braces.

In addition to its extensibility, Python is an interpreted language, which makes it slower than most compiled languages. As you might expect, Python is highly mature, with a huge library ecosystem and a huge professional community.

When to use rust

Rust is used in system development, operating system, enterprise system, microcontroller application, embedded system, file system, browser component, virtual reality simulation engine, etc.

When performance is important, rust is a common language because it can handle large amounts of data well. It can handle CPU intensive operations, such as executing algorithms, which is why rust is more suitable for system development than python.

Rust ensures memory security, allowing you to control thread behavior and resource allocation between threads. This allows you to build complex systems, which gives rust an advantage over python.

In conclusion, you should use rust when:

  • Your project needs high performance
  • You’re building complex systems
  • You value memory security, not simplicity

When to use Python

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

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

  • Easy to write
  • agile
  • Contains a large number of data oriented packages and libraries
  • Supported by excellent tools and library ecosystem

You should use Python when:

  • You need a flexible language to support web development, data science and analysis, as well as machine learning and AI
  • You value readability and simplicity
  • You need a language that is friendly to beginners
  • You prefer simple syntax and fast development to performance

Why can rust replace Python

Given the rapid popularity and wide use cases of rust, it seems almost inevitable that it will surpass Python in the near future. Here are some reasons.

performance

One of the main reasons rust outperforms Python is performance. Because rust is compiled directly into machine code, there is no virtual machine or interpreter between your code and the computer.

Another key advantage over Python is rust’s thread and memory management. Although rust doesn’t have garbage collection capabilities like python, the compiler in rust forces checking for invalid memory reference leaks and other dangerous or irregular behavior.

Compiled languages are usually faster than interpreted languages. But what puts rust at a different level is that it’s almost as fast as C and C + +, but there’s no overhead.

Let’s take a look at an example of an O (log n) program written in Python, and use an iterative method to calculate the time required to complete the task:

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 take a look at the timing o (log n) program written with rust using the iterative method

>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

Without any optimization techniques, it takes 4.6 microseconds for rust and 8.6 microseconds for Python to perform similar operations on the same machine. This means that Python takes almost twice as much time as rust.

memory management

Python, like most modern programming languages, is designed to be memory safe. However, rust’s memory security is beyond Python’s reach, even without garbage collection.

Rust adopts a unique way to ensure memory security, which involves ownership system and borrow checker. Rust’s borrowing checker ensures that references and pointers do not exceed the data they point to.

Error checking and diagnosis

Python, like other languages, provides error checking and logging mechanisms. But there’s some contrast between rust and python when it comes to letting developers know what’s wrong.

Take a typical example of 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 output

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

Here, rust recommends possible variables that you might want to enter. Python will only throw errors, not suggest how to fix them.

for instance:

fn main() {
  let grass = 13;

  grass += 1;
}

This code raises an error because variables in rust are immutable by default. Unless it has a keywordou’'t, otherwise it cannot be changed.

Error:

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

Error correction:

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

  _grass += 1;
}

As you can see, now it doesn’t cause any mistakes. In addition, rust does not allow different data types to interoperate unless they are converted to the same type.

As a result, maintaining the rust code base is usually easy. Rust does not allow changes unless specified. Python does allow this property to change.

Compared with most compiler languages, rust is favored for its high speed, guaranteed memory security, super reliability, consistency and user friendliness. In programming, we have come to the point where speed begins to become effortless.

With the development of technology, it becomes faster and faster, trying to do more things in a shorter time, without so many tradeoffs. Rust helps to do this without getting in the way of developers. When technology tries to push the boundaries that can be achieved, it will also consider the security and reliability of the system, which is the main idea behind rust.

Parallel computing

In addition to speed, python has limitations in parallel computing.

Python uses global interpreter lock (GIL), which encourages only one thread to execute at the same time to improve single thread performance. This process is a hindrance because it means you can’t use multiple CPU cores for intensive computing.

community

As mentioned earlier, 86% of the respondents in stack overflow’s 2020 developer survey named rust as their favorite programming language in 2020.

Rust and python: why rust can replace Python

Similarly, respondents to the 2020 hackerrank developer Skills report listed rust as the top 10 programming languages they plan to learn next:

Rust and python: why rust can replace Python

In contrast, the 2019 survey placed rust at the bottom of the list, indicating that the rust developer community is growing rapidly.

Rust and python: why rust can replace Python

As these data show, rust is becoming part of the mainstream developer community. Many big companies are using rust, and some developers even use it to build libraries for other programming languages. Famous rust users include Mozilla, Dropbox, atlassian, NPM and cloudflare.

Amazon Web service also uses rust for performance sensitive components in lambda, EC2 and S3. In 2019, AWS announced its sponsorship of the rust project, and since then provided the AWS development kit for rust.

Companies are increasingly replacing slower programming languages with more efficient programming languages, such as rust. No other language can balance simplicity with speed like rust.

summary

Rust has developed into a common programming language, and its adoption rate has increased. Although Python has a strong position in the machine learning / data science community, rust is likely to be used as a more efficient back end for Python libraries in the future.

Rust has great potential to replace python. In the current trend, as the preferred programming language for application, performance and speed, rust is not only a programming language, but also a way of thinking.