luke cross
luke cross

Reputation: 331

StringBuilder - setLength(0) vs new instantiate, what is better?

i have a loop (repeated 2 times every iteration when i'm received data from Bluetooth), and i'm using StringBuilder for append the data separate and on final process i need clear the StringBuilder obj,

I'm using now new instantiate, but, i already used .setLength method, which is better than .setLength or new instantiate?

Example of code that receive data from Bluetooth device:

 private void receive(byte[] data) {
     peso.append(new String(data));
     receiveText.setText(peso.toString().replaceAll("(\\r|\\n)", "")+" Kg"); 
     // int i = Integer.parseInt(peso.toString().replaceAll(("\\r|\\n"), ""));
     Log.i("Val of append actual", String.valueOf(peso));

     if(peso.length() >= 3) 
         peso = new StringBuilder();

 }

Other details: I know the max size for my "peso", this is can help on the choice?

Upvotes: 2

Views: 1874

Answers (4)

Moz
Moz

Reputation: 119

The better is to perform ahead checkup before appending any data on your StringBuilder or StringBuffer

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109597

I have even read that new StringBuilder was faster in one instance. So that is more or less an irrelevant micro-optimisation. Profile it in your case. I would give an initial capacity: new StringBuilder(64).

Remarks:

  • Currently if (peso.length() >= 3) is probably for testing.
  • Specify the Charset of the data bytes. Best StandardCharsets.UTF_8.
  • Logging is slow; remove it.
  • Regex is slow. Below is the non-regex replace.
  • \R is for any newline, \n, \r\n, \r, NEL.

So:

 private void receive(byte[] data) {
     peso.append(new String(data, StandardCharsets.ISO_8859_1));
     String pesoS = peso.toString();
     //receiveText.setText(pesoS.replaceAll("\\R", "")+" Kg");
     receiveText.setText(pesoS.replace("\r", "").replace("\n", "")+" Kg"); 
     Log.i("Val of append actual", pesoS);

     if (peso.length() >= 3) 
         peso = new StringBuilder(16);
 }

Upvotes: 2

Umar Tahir
Umar Tahir

Reputation: 625

I am not sure about your use case. But anyhow, new instantiate is always a good option rather than setting length to zero, it shows better intention of code as your code will be more understandable and readable.

The performance difference is really negligible, but your code will be simpler.

Upvotes: 3

Shubham Jain
Shubham Jain

Reputation: 33

Instantiating can be slow, because creating a new Object takes time, but deletion of content from StringBuilder requires no memory allocation process for its internal array, which makes the process better and faster.

Upvotes: 2

Related Questions