HACKER Q&A
📣 anandnair

Why is Rust faster than C++ for calculating the sum of 1M numbers?


I did a benchmark of Rust, C++, Go, Node, Python, Ruby, etc to understand the execution time of a program that simply calculates the sum of 1 million numbers starting with 1. While C++ took around 3.5ms, Rust completed it in under 50ns. What could have been the reason why Rust performed significantly faster?

Full results can be viewed at - https://anands.me/blog/benchmarking-rust-go-cpp-node


  👤 somerando7 Accepted Answer ✓
C++ was probably compiled without optimizations. In a compiled binary there won't even be any calculations done - see for yourself https://godbolt.org/z/Mhhzhdr7c

👤 DemocracyFTW2
I think there was a story about a mainframe salesman who at demonstration time with the customer started the usual demo program. The perspective customer then suggested to leave for lunch and come back when the machine had finished—but then the printer already started to churn out pages, after just a few seconds. Turned out the new compiler was smarter than the old one and had simply erased all the inconsequential computations of the demo code which made it look like magic.

Apocryphal, from memory, many details probably wrong.


👤 compressedgas
Rust ran the loop at compile time.

👤 anandnair
[Update] - I ran the code again with proper compiler optimizations and then C++ performs slightly faster than Rust, thus making it the fastest among all.