开发者

Quickest & most efficient way of formatting a String

What is the quickest way for converting a date which is a str开发者_如何学运维ing with the format "20110913" to "2011-09-13" in Java.


Use java.text.DateFormat:

DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
inputFormat.setLenient(false);
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date inputDate = inputFormat.parse("20110913);
System.out.println(outputFormat.format(inputDate));


I did some simple profiling and found some interesting results.

public static String strcat(String ori){
    return ori.substring(0, 4) + '-' + ori.substring(4, 6) + '-' + ori.substring(6);
}

public static String sdf(String ori){
    try {
        SimpleDateFormat in = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd");
        Date temp = in.parse(ori);
        return out.format(temp);
    } catch (ParseException ex) {
        Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

public static String sb(String ori){
    return new StringBuilder(10).append(ori.substring(0, 4)).append('-').append(ori.substring(4, 6)).append('-').append(ori.substring(6)).toString();
}

public static String nio(String ori){
    byte[] temp = ori.getBytes();
    ByteBuffer bb = ByteBuffer.allocate(temp.length + 2);
    bb.put(temp, 0, 4);
    byte hyphen = '-';
    bb.put(hyphen);
    bb.put(temp, 4, 2);
    bb.put(hyphen);
    bb.put(temp, 6, 2);
    return new String(bb.array());
}

public static String qd(String ori){
    char[] result = new char[10];
    result[4] = result[7] = '-';

    char[] temp = ori.toCharArray();
    System.arraycopy(temp, 0, result, 0, 4);
    System.arraycopy(temp, 4, result, 5, 2);
    System.arraycopy(temp, 6, result, 8, 2);
    return new String(result);
}

public static void main(String[] args) {
    String ori = "20110913";
    int rounds = 10000;
    for (int i = 0; i < rounds; i++) {
        qd(ori);
        nio(ori);
        sb(ori);
        sdf(ori);
        strcat(ori);
    }
}

With the above few methods, I ran the test three times and the results(averaged) are as follow:-

sb      15.7ms
strcat  15.2ms
qd      27.2ms
nio     137.6ms
sdf     582ms

The test is ran using JDK 7. Do take note that this is not an extensive profiling as there are a lot of optimization that can be done (e.g. caching the SimpleDateFormat, StringBuilder). Also, this test is not multithreaded. So, do profile your own program! p.s. the strcat is faster than sb is not what I expected. I guess the compiler optimization plays a big role here.


Use a StringBuilder, append the substrings inserting '-' chars in between them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜