5

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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Charlie
  • 4,827
  • 2
  • 31
  • 55
  • using the `StringBuilder` in this instance doesn't seem to add any value, you would typically use it to append values to a buffer then return that string once complete. You may as well just use a single `string` than a `StringBuilder` instance here. – Ric Nov 06 '15 at 10:09
  • 1
    Why not just use `return System.IO.File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Registry\\" , postalCode , ".html"));` ? – Thomas Ayoub Nov 06 '15 at 10:09
  • @Charlie see SaverioTerracciano's answer for more detail – Ric Nov 06 '15 at 10:18
  • There is no reason (Really no reason) to use string builder here. it cant be even wise. – M.kazem Akhgary Nov 06 '15 at 10:22

7 Answers7

4

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");
Peter
  • 27,590
  • 8
  • 64
  • 84
2

You are actually creating 4 strings here. The first one is AppDomain.CurrentDomain.BaseDirectory + "Registry\\".
The second one is when you add + postalCode to that string.
The third one when you add + ".html".
The fourth one when you call fileName.ToString().

If you want to use StringBuilder, you should do it like this:

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

As Hans Kesting kindly reminded me, you are not really creating 4 strings. The compiler optimizes it to one call to String.Concat().

Domysee
  • 12,718
  • 10
  • 53
  • 84
  • 2
    Not quite: `string + string + string` is translated by the compiler into a single call to [String.Concat](https://msdn.microsoft.com/en-us/library/system.string.concat.aspx) – Hans Kesting Nov 06 '15 at 10:23
  • @HansKesting yea thats true, I just wanted to show what would happen without compiler optimizations – Domysee Nov 06 '15 at 10:27
  • @HansKesting thanks for the correction though, I figured that the compiler would do some kind of optimization, just didn't know exactly what it was. – Domysee Nov 06 '15 at 10:32
2

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"));
}
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

In your case, it doesn't make sense to create first a StringBuilder and then a string.

Strings are immutable in C#, and when you need to make changes to them (Replace, Append, etc.) another string is created in the string pool. The allocation of such has a cost, and in case of several different operations this cost add up and it becomes really expensive.

StringBuilder is an object that can internally change, and is much faster (has a smaller cost) for the upsaid operations, hence it's preferable to use it.

The point in which one is better than the others changes according to the scenario, but as a rule of thumb, if you find yourself changing over and over in the same method the same string, it might be a good idea to use a StringBuilder instead.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
1

You could also use string.Format. It uses StringBuilder internally.

In your case:

    var fileName = string.Format("{0}Registry\\{1}.html", AppDomain.CurrentDomain.BaseDirectory, postalCode);

Is String.Format as efficient as StringBuilder

Community
  • 1
  • 1
Dom84
  • 852
  • 7
  • 20
1

IO operations (even File.Exists) is more time consuming than String creating; you can't avoid File.Exists test that's why, IMHO, the readability is that matters the most:

  1. String formatting
  2. No redundant if

Implementation:

internal bool isFileExists() {
  return File.Exists(String.Format("{0}Registry\\{1}.html", 
    AppDomain.CurrentDomain.BaseDirectory,
    postalCode));
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

It looks weird isFileExists() doesn't use postalCode parameter. Is it just an example or piece of a real code?

I suggest you not to use File.Exists() thousands of times. Make a hashtset with file names and look it up instead.

enkryptor
  • 1,574
  • 1
  • 17
  • 27