Dear juggers, Mumpung lg hot2nya bahas thread puts vs System.out.println, gw ada 1 challenge utk optimize string to double conversion method dari class java.lang.Double:
public static Double valueOf(double d) Kenapa gw butuh utk optimize ini? Krn di project yg sedang gw kerjakan skr, method valueOf memakan 90% ! process time dr keseluruhan process. FYI, data yg dibaca sekitar 10 ribu (nantinya akan jadi ratusan ribu), setiap row terdiri dari 8 column, di mana setiap column-nya berisi data seperti ini: 13.4375:17.1875:22.5:22.8125:23.4375:3:5:4:3:3:3:5:5:3:4:4:5:3:2:6:2:5:3:6:4:2:5:6:3:5:3:2:7:6:5:2:3:6:5:5:2:4:6:4:6:5:3:4:5:3:3:3:5:6:5:2:2:6:7:5:1:3:4:7:6:4:2:1:5:4:3:3:4:5:6:3:1:6:3:5:1:4:2:3:3:3.5:3.75:3.75:4:3.75:3:3.25:5.25:5:5:2.75:2.75:5.25:4.25:5.25:1.5:4:3.75:5:4.75:3:5:3.75:3.5:4.25:2.25:3.5:6.25:4.5:5.25:2.75:2.75:4.75:6.25:4.75:2.75:2.5:3.25:4:4.5:2.75:4.25:5.5:3.75:4.25:2.5:4.25:4.5:4.25:5.25:3.75:2.75:3.5 Waktu yg dibutuhkan utk meload semua data ini adalah 4547 ms. Kemudian saya mencoba utk menggantikan Double.valueOf method dgn method bikinan saya sendiri, & mendapatkan hasil 3718 ms. Code-nya adalah sbb: ============================================== public class ConversionHelper { public static double stringToDouble(String s) { char[] cc = s.toCharArray(); int length = cc.length; if (length == 0) return 0; int i = 0; double negation = 1; if (cc[0] == '-') { negation = -1; i++; } int point = -1; int value = 0; for (; i<length; i++) { if (cc[i] == '.') point = i; else value = value * 10 + cc[i] - '0'; } int divider = 1; if (point > -1) divider = pow10(length - point - 1); return negation * value / divider; } private static int pow10(int n) { int result = 1; for (int i=0; i<n; i++) { result *= 10; } return result; } } ============================================== Ditest dengan looping 1 juta kali: ============================================== @Test public void testPerformance() { long t1 = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { // Double.valueOf("-12.3456"); ConversionHelper.stringToDouble("-12.3456"); } long t2 = System.currentTimeMillis(); System.out.println("Elapsed time = " + (t2 - t1) + " ms"); } ============================================== Hasilnya adalah: - Double.valueof(String): Elapsed time = 344 ms - ConversionHelper.stringToDouble: Elapsed time = 157 ms Sori panjang banget :D Thx kalo udah baca smp di sini. Skr saatnya utk menerima challenge utk mendapatkan hasil yg lebih optimal ;) regards, T Budi S