开发者

calendar.getInstance() or calendar.clone()

开发者 https://www.devze.com 2022-12-26 05:10 出处:网络
I need to make a copy of a given date 100s of times (I cannot pass-by-reference). I am wondering which of the below two are better options

I need to make a copy of a given date 100s of times (I cannot pass-by-reference). I am wondering which of the below two are better options

new开发者_如何学GoTime=Calendar.getInstance().setTime(originalDate);

OR

newTime=originalDate.clone();

Performance is of main conern here.

thx.


I would use

newTime= (Calendar) originalDate.clone();


  1. My gut tells me, that clone() will be faster.
  2. Why not try it with a quick benchmark [*]?
  3. Consider using just the long value of date.getTime(), if you don't have to do calendar calculations.

[*]

private static final int N = 100000;

public static void main(final String[] args) throws Exception {

    final Date date = new Date();

    {
        final long start = System.currentTimeMillis();
        for (int i = 0; i < N; i ++) {
            final Date date2 = (Date) date.clone();
        }
        final long end = System.currentTimeMillis();
        System.out.println("Clone: " + (end - start) + " ms");
    }
    {
        final long start = System.currentTimeMillis();
        for (int i = 0; i < N; i ++) {
            final Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            final Date date2 = cal.getTime();
        }
        final long end = System.currentTimeMillis();
        System.out.println("Caldendar.setTime: " + (end - start) + " ms");
    }
}

Results:

Clone: 13 ms
Caldendar.setTime: 317 ms

PS I'm not sure, if you really need a Calendar, or a Date, so feel free to modify the test...

(In response to the comment: To improve test accuracy, you can also run the tests individually, increase the value of N, ...)


In Scala I would do a clone() and a cast to Calendar with .asInstanceOf[Calendar] like:

val now = Calendar.getInstance()
val newDate = now.clone().asInstanceOf[Calendar]


My approach would be to go for option 1) and then make sure the application is thoroughly profiled to check for bottlenecks. It may be that the above code is not an issue at all in the overall performance of the application at the end of the day.


I cannot pass-by-reference

You sure can't. There is no such thing in Java. But I would review the requirement. What is the actual risk that someone is going to modify the Date if you pass around the same one all the time? and can you control that? e.g. by checking getTime() before and after each call, and throwing an RTE if it changes?

0

精彩评论

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