java - Remove the delimiter , at the end -


  string prefix = ""; For (string server id: server ids) {sb.append (prefix); Prefix = ","; Sb.append (serverId); }  

The following code runs faster than the code above. The "," prefix object creates unnecessary objects at every frequency. The above code takes 86324 nanoseconds, whereas my only takes 68165 nanoseconds.

  list & lt; String & gt; L = arrays.asList ("Suresh 1", "Suresh 2", "Suresh 4", "Suresh 5"); Stringbuff l1 = new stringbuffer (); Int sz = l.size (); Int i = 0; Long T = System.nanoTime (); For (string s: l) {l1.append (s); If (i! = Sz-1) l1.append (","); I ++; }} Tall T2 = system Nano time (); System.out.println ((T2-T)); Println (L1); // Time taken for the above code is 68165 nanose seconds SURESH1, Suresh 2, Suresh 4, Suresh 5  

Please tell me which ur is better in the scene.

Some points:

  • My code lets you know the number of elements Do not require -front In other words, this is the Iterable & lt; String & gt;
  • Why did you use StringBuffer StringBuilder ?
  • "empty prefix object" is created only once ... Are you sure that there is no reference in the context of an empty string anywhere in your code?
  • Which code do you find simpler to read? In most cases it is likely to be more important than the time. (Currently, your code does not have enough open hair in your code, for example ...)
  • Why not use the library method in the first place (like the Causes of < Code> joiner class)?
  • Do not use this short time in the benchmark How accurate are you with your system clock?

Edit: Now an option that addresses the first point, this change will be:

  boolean first = true; Stringbuilder builder = new stringbiller (); (String value: value) {if (first) {first = false; } Other {builder.epend (","); } Builder.append (value); }  

Or if you really prefer to use a counter:

  int i = 0; Stringbuilder builder = new stringbiller (); For (string value: value) {if (i! = 0) {builder.append (","); } Builder.append (value); I ++; }  

Comments

Popular posts from this blog

Eclipse CDT variable colors in editor -

AJAX doesn't send POST query -

wpf - Custom Message Box Advice -