This little “poor-developer filter” was discussed and solved many times.

Despite the number of discussions it spur, and the many suggested ways to solve the problem, the question regarding which solution would be the most efficient, remained unclear. Maybe because its original goal was to screen “bad” developers rather than actually solve the problem efficiently or demonstrate creativity. It was also said that during an interview, solving the problem in more efficient less readable manner would disqualify the developer.

The FizzBuzz problem seems so naive and simple to solve, that it becomes an even more intriguing task to optimize it. So I’ve looked around the various suggestions (more than 80 languages!), and isolated the key ways to solve the problem. Then I added a simple timing and below are the results. Which FizzBuzz solution is the most efficient?

It seems that there are 4 main patterns to solve the FizzBuzz problem:

- Using modulo and int equality test.
- Using modulo and string equality test.
- Count 3 and 5 down or up as
*i* progress (testing counts of 3 and 5).
- Using some bitwise trickery.

I’m using C# in the implementation example, yet the above methods apply to all languages (possibly languages will deffer being better than others comparing ints vs. comparing strings).

Note that I’m using the + sign to concatenate the strings in my examples, yet a more efficient way in C# will be to use StringBuilder. @Thanks Matt!

As shown below, the most effective methods were the ones with: 1. the least int equality tests, and 2. those using less modulo.

The most efficient? we almost have a tie between the following 3 marked in yellow.

Comparing int values (in loop), using 4 (in loop) modulo operations and chained if..else:

Comparing int values, using 2 (in loop) modulo operations and 4 (in loop) int equality tests:

Comparing strings, using 2 (in loop) modulo operations:

Counting up, using 2 single (out of loop) modulo operations:

Counting down, using no modulo operations, chained if..else:

All Bitwise operations (using predefined 0-15 numbers mask):

**@Download the full C# code**

Can you find a more efficient way?

For more exploration, visit this discussion: http://c2.com/cgi/wiki?FizzBuzzTest .

### Like this:

Like Loading...

Pingback: The Complete Guide to Nailing Your Next Interview()