views:

234

answers:

4

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

newTime=Calendar.getInstance().setTime(originalDate);

OR

newTime=originalDate.clone();

Performance is of main conern here.

thx.

A: 

I would use

newTime=originalDate.clone();
armandino
Why would you use it instead of a 'new'?
pnt
A: 

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.

nahojkap
+2  A: 
  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, ...)

Chris Lercher
Your test is flawed as the second loop benefits from the cache being loaded and warmed up from the first loop. You need to run each test case separately.
Steve Kuo
@Steve: It's easy to do that: Just comment out the one you don't want to run... For me, it doesn't change the results. Actually, it's rather irrelevant anyway, since the *second* one is slower... (BTW, I just wanted to present an easy, quick and dirty way of testing this, in a very short format)
Chris Lercher
A: 

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?

EJP
this is defensive coding...due to the nature of the business we are in, the accidental change in the date might be a huge law suit...
Pangea