Which FizzBuzz solution is the most efficient?

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:

Share on:

Like this:

Well, since you said this is all c# and you are going for efficiency, you really should get rid of the string concatenation += operators. Use a StringBuilder, or Console.WriteLine each string directly. Using string concatenation in a loop is a big performance problem because it allocates new memory on the heap each time you use it. In other words, s += “foo” needs three separate memory locations (the original value of s, the value of “foo” and the new value of the result).

You’re right… thanks for the comment!
For reference, I’ve added a note to the post.

Guest

As Matt mentioned , the string concatination is the real bottleneck. The solutions are all pretty similar in performance and only differ by the number of result+= statements they use which is why the bitwise version appears faster.

lavaeagle

Just for kicksI wrote this as ternary statements in PHP in one line. Basically unreadable but funny.