1

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?

luke cross
  • 321
  • 1
  • 2
  • 19
  • 2
    Can you share your piece of code in which you are doing this, for clarity. – Umar Tahir Jan 08 '20 at 13:37
  • 1
    You're unlikely to to see any significant difference. Keeping the variable in a small scope and creating a new object would work just fine and not provide any surprises. Using `setLength(0)` won't give you any performance advantages, but your code may end up looking "weirder". – Kayaman Jan 08 '20 at 13:38
  • You can [edit] your post and add a [mcve]. – Abra Jan 08 '20 at 13:39
  • 1
    The OP clearly knows *how*, which the duplicates addressed. This question is about whether it matters which way it's done (which it most likely doesn't). – Kayaman Jan 08 '20 at 13:43
  • Sorry, i added code now, thanks all! – luke cross Jan 08 '20 at 13:45
  • If a performance is so critical it's better to to use `setLength(0)`, but looking on your code there are other expensive operations like `replaceAll("(\\r|\\n)"` and string concatenation `" Kg"` – edwgiz Jan 08 '20 at 14:12
  • It doesn't matter. In your above code, you could do two or three more important optimizations, but they hardly matter either. The blue tooth communication costs much more. – maaartinus Jan 08 '20 at 14:27

3 Answers3

3

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.

Umar Tahir
  • 585
  • 6
  • 21
  • 1
    *"but your code will be shorter and simpler"*... can you add an example to help me understand how? – Harshal Parekh Jan 08 '20 at 13:58
  • I should have used word "simpler only" but anyhow sb.setLength(0); or sb.delete(0, sb.length()); doesn't depict true intention of code. It is better for readability that we use StringBuilder v = new StringBuilder(); – Umar Tahir Jan 08 '20 at 14:07
2

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.

Shubham Jain
  • 33
  • 1
  • 2
2

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);
 }
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I'll remove Log after the app finalized, this is debug version, thanks for this tips! – luke cross Jan 08 '20 at 14:22
  • A curiosity, why need specify Charset? – luke cross Jan 08 '20 at 14:22
  • Without explicit parameter, the default platform encoding is used. For crossplatform data (a file you provide, remote data; net/database) it is guaranteed to create a non-portable (=wrong) application. So that would be smelly code. Even use `Charset.getDefaultCharset()` to clearly indicate you are using local data. – Joop Eggen Jan 08 '20 at 14:25
  • I'll added UTF-8 because i need receive data from Arduino (with Bluetooth) and i'll send the data to Firebase Database. Thanks – luke cross Jan 08 '20 at 14:26
  • 1
    *"Regex is slow."* In fact, the major overhead is the parsing. Using a preparsed regex is nearly as performant as fixed string search. – Dávid Horváth Dec 25 '20 at 04:59