fork(4) download
  1. import java.io.IOException;
  2. import java.io.UnsupportedEncodingException;
  3. import java.nio.ByteBuffer;
  4. import java.nio.CharBuffer;
  5. import java.nio.charset.CharacterCodingException;
  6. import java.nio.charset.Charset;
  7. import java.nio.charset.CharsetDecoder;
  8. import java.text.ParseException;
  9.  
  10. class Main{
  11. public static void main(String[] args) throws IOException, ParseException {
  12. StringBuilder sb1 = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
  13. for (int i=0;i<15;i++) {
  14. sb1.append(sb1);
  15. }
  16. System.out.println("Size of buffer: "+sb1.length());
  17. byte[] src = sb1.toString().getBytes("UTF-8");
  18. StringBuilder res = null;
  19.  
  20. long startTime = System.currentTimeMillis();
  21. for (int i=0;i<100;i++)
  22. res = testStringConvert(src);
  23. System.out.println("Conversion using String time (msec): "+(System.currentTimeMillis()-startTime));
  24. if (!res.toString().equals(sb1.toString())) {
  25. System.err.println("Conversion error");
  26. }
  27.  
  28. startTime = System.currentTimeMillis();
  29. for (int i=0;i<100;i++)
  30. res = testCBConvert(src);
  31. System.out.println("Conversion using CharBuffer time (msec): "+(System.currentTimeMillis()-startTime));
  32. if (!res.toString().equals(sb1.toString())) {
  33. System.err.println("Conversion error");
  34. }
  35. }
  36.  
  37. private static StringBuilder testStringConvert(byte[] src) throws UnsupportedEncodingException {
  38. String s = new String(src, "UTF-8");
  39. StringBuilder b = new StringBuilder(s);
  40. return b;
  41. }
  42.  
  43. private static StringBuilder testCBConvert(byte[] src) throws CharacterCodingException {
  44. Charset charset = Charset.forName("UTF-8");
  45. CharsetDecoder decoder = charset.newDecoder();
  46. ByteBuffer srcBuffer = ByteBuffer.wrap(src);
  47. CharBuffer resBuffer = decoder.decode(srcBuffer);
  48. StringBuilder b = new StringBuilder(resBuffer);
  49. return b;
  50. }
  51. }
Success #stdin #stdout 4.64s 246080KB
stdin
Standard input is empty
stdout
Size of buffer: 851968
Conversion using String time (msec): 1018
Conversion using CharBuffer time (msec): 3629