SHARE
TWEET

faster java output

DulcetAirman Aug 1st, 2018 86 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin.playground;
  2.  
  3. import java.io.FilterOutputStream;
  4. import java.io.OutputStream;
  5. import java.io.PrintStream;
  6. import java.lang.reflect.Field;
  7.  
  8. public final class SomeClass {
  9.     final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE };
  10.  
  11.     static int stringSize(int x) {
  12.         for (int i = 0;; i++)
  13.             if (x <= sizeTable[i])
  14.                 return i + 1;
  15.     }
  16.  
  17.     static boolean increment(byte[] buf, int off) {
  18.         if (buf[off] == 0) {
  19.             buf[off] = '1';
  20.             return true;
  21.         }
  22.         if (buf[off] == '9') {
  23.             buf[off] = '0';
  24.             return increment(buf, off - 1);
  25.         }
  26.         buf[off]++;
  27.         return false;
  28.     }
  29.  
  30.     public static void main(String... args) throws Throwable {
  31.         final long start = System.nanoTime();
  32.         final int n = 10000000;
  33.         // IntStream.rangeClosed(0, lastNumber).forEach(System.out::println);
  34.         final int size = stringSize(n);
  35.         byte[] buf = new byte[size + 1];
  36.         buf[size-1] = '0';
  37.         buf[size] = '\n';
  38.         final Field field = FilterOutputStream.class.getDeclaredField("out");
  39.         field.setAccessible(true);
  40.         OutputStream out = (OutputStream) field.get(System.out);
  41.         int off = size - 1;
  42.         final int last = size - 1; // least significant byte
  43.  
  44.         for (int i = 0; i < n; i++) {
  45.             if (increment(buf, last))
  46.                 off--;
  47.             out.write(buf, off, size - off+1 );
  48.         }
  49.         final long end = System.nanoTime();
  50.         System.out.println("====");
  51.         System.out.println(end - start);
  52.     }
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top