0

In Rust High Performance, on page 27, the author wrote:

The problem is that if you are trying to print an integer, for example, a bottleneck appears. That's what happened some time ago to Robert Grosse, and he wrote an article about it. Long story short, he had to force the copying of the integer. How did he do that? Well, it's as simple as creating a scope that will return that integer. Since integers implement Copy, the integer will be copied to the scope and then returned, effectively copying it to the macro: let my_int = 76_u32; println!("{}", {my_int});

Why does the author claim it is a bottleneck print an integer? Such that it even results in a workaround of creating a new scope for the sole purpose of copying the passed-in integer?

I searched for Robert Grosse but couldn't find the mentioned article.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jim
  • 450
  • 2
  • 10

1 Answers1

2

It looks like the reverenced article is how copying an int made my code 11 times faster by Robert Grosse.

The problem was apparently the following (spelled out about a third down the page):

while Rust knows that the borrow is immutable [nb: println! always implicitly borrows its parameters], this information is sadly not passed to LLVM. This means that the LLVM optimizer sees that a pointer to size is being passed to some function and just gives up, leaving the following code to assume that size holds an arbitrary value.

Robert then shows the assembly, and that clarifies things: it's not that println! bottlenecks the code, it's that the println! causes an optimization failure (or a deoptimisation): LLVM's assumed that println! might keep a handle on &size, so on every iteration it had to re-load the size, perform the modulo, and perform a bounds check.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • the more and more println prove being bad. – Stargateur Apr 21 '23 at 08:42
  • I don't think it has anything to do with `println` itself, it has to do with the expressivity of the IR, and the visibility of the thing to the optimiser. You can replace `println!` by an `extern` function and you will see similar issues. – Masklinn Apr 21 '23 at 08:53
  • it's not the first time I hear about problem with macro println, https://stackoverflow.com/questions/75939406/in-rust-why-does-integer-overflow-sometimes-cause-compilation-error-or-runtime – Stargateur Apr 21 '23 at 11:18