How to Clear or Empty a Stringbuilder

How can I clear or empty a StringBuilder?

Two ways that work:

  1. Use stringBuilderObj.setLength(0).
  2. Allocate a new one with new StringBuilder() instead of clearing the buffer. Note that for performance-critical code paths, this approach can be significantly slower than the setLength-based approach (since a new object with a new buffer needs to be allocated, the old object becomes eligible for GC etc).

Is this a good way of clearing a StringBuilder?

Before I post my answer I am assuming that you are using StringBuilder in a loop and every few iterations you may want to empty it and start with an empty StringBuilder. In that case I can think of two approaches:

  • invoke setLength(0) on the string builder you are using. I prefer this over delete as I feel this is more neat.
  • Or allocate a new one instead rather than clearing the buffer. It may not be an ideal option but still an option.

StringBuilder - Reset or create a new

I think StringBuilder#delete(start, end) is still expensive call, you should do:

stringBuilder.setLength(0);

to reset it.


UPDATE: After looking at source code of StringBuilder It seems setLength(int) leaves old buffer intact and it is better to call: StringBuilder#trimToSize() after above call which attempts to reduce storage used for the character sequence.

So something like this would be more efficient:

stringBuilder.setLength(0); // set length of buffer to 0
stringBuilder.trimToSize(); // trim the underlying buffer

android clear a string builder

Try using sb.delete(0,sb.length());

EDIT:

StringBuilder sb2 = new StringBuilder();
sb2.delete(0,sb2.length());

In the code above, you are trying to delete contents of an empty StringBuilder.

This can't be done.

best way to clear contents of .NET's StringBuilder

If you're doing this in .NET 2.0 or 3.5, write an extension method to do it like this:

/// <summary>
/// Clears the contents of the string builder.
/// </summary>
/// <param name="value">
/// The <see cref="StringBuilder"/> to clear.
/// </param>
public static void Clear(this StringBuilder value)
{
value.Length = 0;
value.Capacity = 0;
}

Then, you can clear it like this:

someStringBuilder.Clear();

Then, when 4.0 comes out, you can ditch your extension method in favor of the 4.0 version.

UPDATE: It's probably not a good idea to set Capacity to zero. That will guarantee reallocations when you append to the builder, if you're reusing the same instance. However, the memory in the instance of the builder is not released until you set the Capacity to a very small value (such as 1). The default value of the Capacity property is 16. You might want to consider using 16, or (though it's less efficient) setting the capacity twice:

  • Set it to 1 or zero to clear the memory
  • Set it to your original Capacity value (which may differ from 16) to restore it.

How to make StringBuilder empty again in .NET 3.5 ?

You can simply;

sb.Length = 0;

How to check if a StringBuilder is empty?

If you look at the documentation of StringBuilder it has only 4 properties. One of them is Length.

The length of a StringBuilder object is defined by its number of Char objects.

You can use the Length property:

Gets or sets the length of the current StringBuilder object.

StringBuilder sb = new StringBuilder();

if (sb.Length != 0)
{
// you have found some difference
}

Another possibility would be to treat it as a string by using the String.IsNullOrEmpty method and condense the builder to a string using the ToString method. You can even grab the resulting string and assign it to a variable which you would use if you have found some differences:

string difference = ""; 

if (!String.IsNullOrEmpty(difference = sb.ToString()))
{
Console.WriteLine(difference);
}

Which one is performance wise to clear a string builder?

Update It turns out that you are using .net 3.5 and Clear was added in .net 4. So you should use Length = 0. Actually I'd probably add an extension method named Clear to do this since it is far more readable, in my view, than Length = 0.


I would use none of those and instead call Clear.

Clear is a convenience method that is equivalent to setting the Length property of the current instance to 0 (zero).

I can't imagine that it's slower than any of your variants and I also can't imagine that clearing a StringBuilder instance could ever be a bottleneck. If there is a bottleneck anywhere it will be in the appending code.

If performance of clearing the object really is a bottleneck then you will need to time your code to know which variant is faster. There's never a real substitute for benchmarking when considering performance.

java stringbuilder deleting a line

My best suggestion is to avoid having two operations done at the same time. Here your attempt to filter out your deleted employee while appending their data to the StringBuilder. Ideally, I would first filter out the employees and then use them to create my String output. With that in mind your method would look like:

public static void display() {

StringBuilder builder = new StringBuilder();

List<Employee> filtered = Arrays.stream(employees)
.filter(employee -> employee.getName() == null)
.collect(Collectors.toList());

filtered.forEach(employee ->
builder.append(employee.getName())
.append("\t ")
.append(employee.getPay())
.append("\n "));

String output = builder.toString();
JOptionPane.showMessageDialog(null,"Staff_No Staff_Name Pay \n" + output);
}

Assuming that you store your employees in an array of Employees, I would basically, stream that array filtering out all entries with a null name, collecting the results in a list.

With that list in hand, I would then go ahead to use the StringBuilder to construct my output message to be shown in the dialog. Note also here, that I do not see any point in having the StringBuilder be a static member of the class. You could very well have it within the context of the method.

With all the above in place, you have two very distinct actions here. One is to filter out all the unwanted entries, and the other being the actual construction of the output string.



Related Topics



Leave a reply



Submit