fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.io.UnsupportedEncodingException;
  7.  
  8. /**
  9.  *@author rpax - http://stackoverflow.com/questions/22441079/is-it-correct-efficient-to-call-trim-after-a-byte-to-string-conversion
  10.  **/
  11. class Test {
  12.  
  13. /**
  14. *
  15. * @param args
  16. */
  17. public static void main(String[] args) {
  18. byte[] barray= new byte[9999999];
  19. barray[0]=72;
  20. barray[1]=101;
  21. barray[2]=0;
  22. barray[3]=108;
  23. barray[4]=111;
  24. barray[5]=33;
  25. for (int k = 6; k < barray.length; k++) {
  26. barray[k]=0;
  27. }
  28. try {
  29. long c=System.nanoTime();
  30. System.out.println(convertFromByteArray2(barray));
  31. long d=System.nanoTime();
  32. long tot_2=d-c;
  33. long a=System.nanoTime();
  34. System.out.println(convertFromByteArray(barray));
  35. long b=System.nanoTime();
  36. long tot_1=b-a;
  37.  
  38. System.out.println(tot_1 +" - "+tot_2+" "+(tot_1*1.0/tot_2));
  39.  
  40. // TODO Auto-generated catch block
  41. e.printStackTrace();
  42. }
  43.  
  44. }
  45. public static String convertFromByteArray(byte[] a) throws UnsupportedEncodingException{
  46. String s = new String(a,"UTF-8");
  47. return s.trim();
  48. }
  49. public static String convertFromByteArray2(byte[] barray) throws UnsupportedEncodingException {
  50. int i=barray.length-1;
  51. while(barray[i--]==0 && i>=0);
  52. return new String(barray,0,i+2,"UTF-8");
  53. }
  54.  
  55. }
  56.  
Success #stdin #stdout 0.21s 380608KB
stdin
Standard input is empty
stdout
Helo!
Helo!
85980366 - 21438869 4.010489825745938