Is it worth the effort to empty a long string?

93 Views Asked by At

I used a StringBuilder to write an SQL query in .NET. After I perform the query, is there a point in manually setting the contents of the string to ""?

I'm guessing this is already being done by the compiler (maybe only with the optimize option enabled).

1

There are 1 best solutions below

3
Mike Nakis On

In C#, you cannot set the contents of a string to "". You cannot set the contents of a string to anything. Strings in C# are immutable.

Perhaps what you meant to say is "is there a point in clearing the StringBuilder?"

In theory, there could be merit in clearing the StringBuilder, if:

  • You are keeping that StringBuilder around and reusing it.
  • You are filling it with huge strings. I mean, really huge. Like megabyte-long strings.

Under the above scenario, it might be worth clearing the StringBuilder after each use, instead of immediately before each reuse.

But you are probably not keeping the StringBuilder around, and even if you are, your SQL queries are probably not megabytes long, so stop worrying about this.

And no, your guess is wrong, the compiler will not do anything about any of this, either with or without optimizations. These are all affairs of the runtime, not of the compiler.