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.
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");
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"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With