Book Image

Rust High Performance

By : Iban Eguia Moraza
Book Image

Rust High Performance

By: Iban Eguia Moraza

Overview of this book

This book teaches you how to optimize the performance of your Rust code so that it is at the same level as languages such as C/C++. You'll understand and fi x common pitfalls, learn how to improve your productivity by using metaprogramming, and speed up your code. You will master the features of the language, which will make you stand out, and use them to greatly improve the efficiency of your algorithms. The book begins with an introduction to help you identify bottlenecks when programming in Rust. We highlight common performance pitfalls, along with strategies to detect and resolve these issues early. We move on to mastering Rust's type system, which will enable us to optimize both performance and safety at compile time. You will learn how to effectively manage memory in Rust, mastering the borrow checker. We move on to measuring performance and you will see how this affects the way you write code. Moving forward, you will perform metaprogramming in Rust to boost the performance of your code and your productivity. Finally, you will learn parallel programming in Rust, which enables efficient and faster execution by using multithreading and asynchronous programming.
Table of Contents (19 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Index

Preface

Welcome to Rust High Performance. In this book, you will get a gentle introduction to high-performance programming by learning how to improve the performance of your Rust code. It will show you how to translate your code from other languages properly by avoiding common bottlenecks, and it will show you how to easily increase the performance of your application using some idiomatic Rust APIs.

You will learn about the great Rust community by finding great crates that will increase the development efficiency while also improving the performance of your application, and you will write examples to use all your knowledge. You will write your own macros and custom derives, and you will learn about asynchronous and multithreaded programming.

Who this book is for

In this book, you will find everything you need to improve the performance of your Rust code; you will learn many tricks and use helpful crates and tools. Therefore, the book is written from the basis that you already have some knowledge of programming in Rust.

This book will not cover the whole world of high-performance programming since it's an incredibly wide topic. You will find a gentle introduction to most of the generic high-performance programming concepts and learn how specific patterns can be used in the Rust programming language.

What this book covers

Chapter 1, Common Performance Pitfalls, helps you learn why translating from languages such as C/C++ can lead to big performance decline, how to improve your algorithms using different Copy/Clone types and references, and understand how cyclomatic complexity can make compiler optimizations less effective.

Chapter 2, Extra Performance Enhancements, takes a step forward to understand some tips and tricks Rust gives us to improve the performance of your applications. After learning about common mistakes in the previous chapters, you will learn how to use the Rust type system to your advantage, creating complex compile-time checks and evaluations. You will also understand the difference between the common standard library collections so that you can choose the right one for your algorithm.

 Chapter 3, Memory Management in Rust, shows you how to improve the memory footprint of your applications by taking advantage of the borrow checker. You will learn about lifetimes and how to properly use them, understand the different representation attributes that will help your data be properly structured in memory, and finally, learn how to create efficient shared pointer structures for your application using standard library types.

Chapter 4, Lints and Clippy, teaches you the power of lints and how to configure them to give you proper suggestions. You'll learn how to configure clippy, an incredibly powerful tool that will point out common errors and potential performance improvements. In this chapter, you will learn the most important clippy lints and use them in your development workflow.

Chapter 5, Profiling Your Rust Application, covers how to use profiling software so that you can easily find performance bottlenecks in your applications. You'll learn how cache misses impact your code and how to find where in the code is the application spending more time. You will learn to fix those bottlenecks and therefore improve the overall performance of the application.

Chapter 6, Benchmarking, discusses how to detect performance critical code and how to benchmark it in both Rust stable and nightly. You will also learn how to set up your continuous integration environment to get performance reports and track them during the development process of your project.

Chapter 7, Built-in Macros and Configuration Items, brings you to the world of attributes that can personalize your code so that you target specific platforms with each section of your code using all of each platform's potential. You will understand how to divide your crate so that not all the code has to be compiled for each use, and you will finally learn how to use nightly features to improve the efficiency of your code and the amount of code to write.

Chapter 8, Must-Have Macro Crates, introduces you to multiple metaprogramming crates—create serializable structures, deserialize data from languages such as JSON or TOML, parse log files, or create a lot of boilerplate code for your data structures. Here, you can understand how to initialize complex static structures and use a proper error handling. Finally, thanks to nightly Rust and plugins, you will be able to create a small web server with a database and even attach to it the fastest template system in existence.

Chapter 9, Creating Your Own Macros, covers how to write your own macros to avoid code boilerplate. You will understand how the new macros 1.1 work and create your first custom derive. Finally, you will learn how compiler plugins internally work and will create your own compiler plugin.

 Chapter 10, Multithreading, outlines how to create multiple threads to balance the work of your application. You will understand the full power of Rust's threads and the synchronization primitives in the standard library. In addition, you will learn how to send information between threads. Finally, you will read about some useful crates that will enable you to implement work stealing algorithms, parallel iterators, and more.

Chapter 11, Asynchronous Programming, helps you understand how asynchronous programming works. Here, you can learn how to develop asynchronous algorithms in Rust, thanks to mio and futures, and learn the new async/await syntax. You can also create asynchronous applications using tokio and WebSockets.

To get the most out of this book

This book assumes some basic knowledge of the Rust programming language. If you are new to Rust, the first few chapters of the official Rust book are a great prelude. Nevertheless, you should have moderate to deep knowledge of at least one programming language; basic knowledge of terminal usage will also be needed.

Having basic knowledge of computer architectures is a plus, along with basic knowledge of high-performance programming in C/C++. They are not required, though, since in this book we will cover all the base theory to understand how the performance improvements work behind the scenes.

You will need a code editor or an IDE to follow the book. Rust has been heavily tested in Microsoft's Visual Studio Code, GitHub's Atom, and IntelliJ's IDEA IDE. I have personally used Atom to write the code examples, but feel free to use your favorite text editor or IDE. You will probably find plugins or extensions for your editor.

In the case of VS Code, Atom, and IntelliJ IDEA, you will find official Rust packages along with unofficial extensions. Personally, I've been using the Tokamak package for Atom.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packtpub.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Rust-High-Performance. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The iterator will not run until you call collect() method or use it in a loop. Those are the moments in which the next() method gets executed."

A block of code is set as follows:

    for row in arr1.iter().cartesian_product(arr2.iter()) {
      print!("{:?}, ", row);
    }

Any command-line input or output is written as follows:

cargo install --no-default-features --features sqlite diesel_cli

Bold: Indicates a new term, an important word, or words that you see onscreen.

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.