Living life by the motto, "You didn't get this far by giving up." It hasn't failed her yet.
Did you know strings are immutable in C#? If you aren't familiar with the StringBuilder class, you might be making inefficient code.
I previously discussed the well-known FizzBuzz challenge and how I was recently challenged to solve it using JavaScript. As I mentioned then, I was additionally asked to solve FizzBuzz in a different situation. This second occasion required me to use C#, and perhaps more importantly, it was under time constraints for a HackerRank test. Though this solve doesn't feature flashy logic like my JavaScript solution, it nevertheless includes an important concept I'd like to address.
For context, the static method fizzBuzz() and its parameter (the end value) were provided and not to be altered, the objective is to print the results to the console, and the instructions specified set values of '3' for Fizz, '5' for Buzz, and '1' for the start. Let's dive in.
public static void fizzBuzz(int n)
{
for (int i = 1; i < n; i++)
{
StringBuilder sb = new();
if (i % 3 == 0) sb.Append("fizz");
if (i % 5 == 0) sb.Append("buzz");
if (sb.ToString().Equals(“”) Console.WriteLine($"{i}");
else Console.WriteLine($"{sb.ToString()}");
}
}
Not too complicated, right? A for-loop that begins at '1', evaluates whether 'i' is divisible by '3' or '5', and writes results to the console. Simple. But wait, what's that StringBuilder class? Why didn't I just use a string variable to capture the results? Let's see what that would look like:
public static void fizzBuzz(int n)
{
for (int i = 1; i < n; i++)
{
string answer = "";
if (i % 3 == 0) answer = "fizz";
if (i % 5 == 0) answer += "buzz";
if (string.IsNullOrEmpty(answer)) Console.WriteLine($"{i}");
else Console.WriteLine($"{answer}");
}
}
This will get the job done, that's certainly true. And while it's not horribly inefficient in this particular circumstance, it’s still not an optimal solution. See, unlike strings in JavaScript, C# strings have a quirk: They're immutable. At each of the logic checks for Fizz and Buzz, the if-statement being satisfied appears to alter the variable 'answer,' but the truth is the existing string assigned to 'answer' has been left on the heap, and a new string has been assigned to 'answer' instead. That lingering string remains in the heap until the garbage collector runs, and that's not great!
Enter the StringBuilder class. Instead of declaring a blank string and "appending" to it, my solution appends to the StringBuilder 'sb'. If its value is blank when I read it out as a string later, then I know 'i' isn't divisible by '3' or '5,' so I should write the value of 'i' to the console instead of the value of 'sb.'
This quirk is a reminder. Programming languages have differences, and those differences do more than influence what they're good or bad at: They influence how we should use them at all.
0 Comments