Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.ToString() creates a new string from StringBuilder, so why not use string directly?

Tags:

c#

I have seen questions related to string builder but was not able to find relevant answer.

My question is "Is it wise to use string builder here? if not how to use it wisely here".

This method is going to run 100000 times. In order to save some memory I used stringbuilder here. but the problem is .ToString() method. Anyway I will have to create a string using .ToString() method so why not initialize filename as string rather than StringBuilder.

internal bool isFileExists()
{
    StringBuilder fileName = new StringBuilder(AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html");
    if (System.IO.File.Exists(fileName.ToString()))
    {
        return true;
    }
    else
    {
        return false;
    }
}

All libraries method use string as a parameter not string builder why? I think I got a lot of confusion in my concepts.

like image 672
Charlie Avatar asked Nov 06 '15 10:11

Charlie


2 Answers

Actually you are not using string builder. You first make a string by:

AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html"

And then feed it to the string builder.

To use StringBuilder correctly:

StringBuilder fileName = new StringBuilder();
fileName.Append(AppDomain.CurrentDomain.BaseDirectory);
fileName.Append("Registry\\");
fileName.Append(postalCode );
fileName.Append(".html");

If you make liners to make strings you can just make the string by:

string filenamestr = AppDomain.CurrentDomain.BaseDirectory + "Registry\\" + postalCode + ".html";

In this case you are making a filepath, so it is recommended to use:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Registry\\" , postalCode , ".html");
like image 51
Peter Avatar answered Sep 29 '22 12:09

Peter


Given what your code do (check if a file exists), the real bottleneck will not be using a string or a stringbuilder but checking if the file really exists... So I would let the system do the concatenation of string and taking care of performances:

internal bool isFileExists()
{
    return System.IO.File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Registry\\" , postalCode , ".html"));
}
like image 24
Thomas Ayoub Avatar answered Sep 29 '22 10:09

Thomas Ayoub