Optimizing FizzBuzz in Rust

https://news.ycombinator.com/rss Hits: 5
Summary

Optimizing FizzBuzz in Rust for Fun and Profit My little cousin is learning Python, and wanted to know about what kinds of questions he could expect to get in coding interviews. I started him off with good ol' FizzBuzz: obsolete for any actual coding interview today (at least, I hope), but good at his level. After a little back and forth getting reminded about how to create range iterators and fixing the order, he landed on this implementation: def basic_fizzbuzz(): for i in range(1, 101): if i%15 == 0: print("FizzBuzz") elif i%3 == 0: print("Fizz") elif i%5 == 0: print("Buzz") else: print(i) A good first shot: it'd get him to the next question without much fuss. But then, by coincidence, I watched an old Prime video and decided to put the question to him: how would you extend this to 7 = "Baz"? He expanded the if-else chain: I asked him to find a way to do it without explosively increasing the number of necessary checks with each new term added. After some hints and more discussion, we arrived at this implementation: def enhanced_fizzbuzzbaz(): for i in range(1, 101): s = "" if i%3 == 0: s+="Fizz" if i%5 == 0: s+="Buzz" if i%7 == 0: s+="Baz" if not s: print(i) else: print(s) Nice and straightforward. But this did get me thinking: how would we make this as performant and extensible as possible? Some quick-and-dirty benchmarking shows that each fizzbuzz (give or take some loop overhead) takes around 105 microseconds. Slow, yes, but not tripping my alarm bells just yet. Python is slow, say less. Adding 'Baz' takes us up to 110 microseconds. Switching to our composable version shaves off a little bit and gets us to around 107 microseconds. Easier on the developer AND marginally more performant, just what I want to see. I'm sure there are further optimizations to be made in Python... but Python's not the tool I reach for when I want to explore optimization potential. So I took this to the natural conclusion of all software, and rewrote it in Rust. pub fn enhanced_fizzru...

First seen: 2025-08-23 20:43

Last seen: 2025-08-24 00:53