3 ms·
> However, I have yet to see one that would actually be better in the real world than the simple, obvious solution. Use counters, avoid modulo, and see a signi
by buro9 11y ago
> However, I have yet to see one that would actually be better in the real world than the simple, obvious solution.
Use counters, avoid modulo, and see a significant performance increase.
Computers suck at division, and FizzBuzz doesn't need division.
The solution is perhaps simpler than the obvious one as even a child could explain how it works.
https://gist.github.com/buro9/5345664#file-fizzbuzz-html https://gist.github.com/buro9/5345664#file-fizzbuzz-html
On my laptop, in Firefox:
Fast: 203ms
Slow: 844ms
- thedufer 11y agoThat depends on how you're defining better. The slow one is somewhat more readable, and since your test runs a million times farther than the 100 that FizzBuzz usually asks for, you're looking at a gain of .6 μs. That's an interesting set of priorities, unless you know something about how often this code runs.
- buro9 11y agoI'm not sure anyone imagines running FizzBuzz in production. It is an interview tool only, first to determine whether the candidate can program, but which can also be used as a basis for some interview questions. The counter example helps to answer whether the candidate understands how numbers are represented by computers and how addition and division function. It also helps to answer whether a candidate knows what, in such trivial code, could (not must) be optimised were the value of n to increase insignificantly. As you say, probing questions about how often the code runs, what the value of n is, or various other questions will all vary the answer. But to suggest that the priorities are wrong is a little silly, most interview questions are wrong to some definition.
- blacksmythe 11y ago>> Use counters, avoid modulo, That is also my solution (although I would use only two counters). Having a background in hardware engineering and hardware optimization, using a modulo operation unnecessarily seems completely foreign to me.