liveBook · Manning

Compiler optimization

As explained in Refactoring to Rust

An optimizing compiler transforms source code while applying semantics-preserving transformations intended to improve runtime efficiency.

Compiler optimization transforms code without changing its intended behavior, aiming to improve runtime efficiency. In Rust, optimized compilation becomes important when measured gains over Python are unexpectedly small. section 6.5

Use benchmarking to make optimization effects concrete:

  • Compile benchmark targets in optimized mode before comparing implementations. section 6.5
  • Measure complete workloads rather than assuming that switching languages guarantees a large speedup. section 6.5

Comparing optimized benchmark results

A Criterion benchmark measures a pure-Python JSON calculation at about 25.6 μs and a Rust extension at about 22.0 μs. The result demonstrates a measured, modest improvement rather than an assumed transformation. section 6.5

$ cd json-sum-benchmark
$ cargo bench
   Compiling json-sum-benchmark v0.1.0
    Finished bench [optimized] target(s) in 2.09s
     Running unittests

running 1 test
test tests::it_works ... ignored

test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out;

     Running unittests
Benchmarking u8: Warming up for 3.0000 s
Benchmarking u8: Collecting 100 samples in estimated 5.0000 s (20B iters)
u8                      time:   [257.13 ps 261.71 ps 266.79 ps]

Benchmarking u128: Warming up for 3.0000 s
Benchmarking u128: Collecting 100 samples in estimated 5.0000 s (10B iters)
u128                    time:   [502.27 ps 510.24 ps 521.03 ps]

Inspect the Cargo benchmark output showing an optimized target and measured timings for different integer operations. section 6.5

How Refactoring to Rust covers it

How deep it goes
Motivates optimization through benchmark results but stops short of explaining compiler transformation internals.
Examples
Uses integer benchmarks and a JSON-summing comparison between pure Python and a Rust extension module.
What it assumes
Assumes familiarity with Rust and Python integration, while introducing optimization through concrete benchmark results.
What you can do after
Evaluate optimized runtime performance with Cargo and Criterion benchmarks instead of relying on language-level assumptions.
How it connects
Connects compiler optimization with Rust, benchmarking, Criterion, Python, and extension modules.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.