Aravind Yarram
Aravind Yarram

Reputation: 80196

calendar.getInstance() or calendar.clone()

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.

Upvotes: 39

Views: 55408

Answers (5)

armandino
armandino

Reputation: 18548

I would use

newTime= (Calendar) originalDate.clone();

Upvotes: 48

johannesemden
johannesemden

Reputation: 31

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]

Upvotes: 3

user207421
user207421

Reputation: 311008

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?

Upvotes: 1

Chris Lercher
Chris Lercher

Reputation: 37778

  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, ...)

Upvotes: 32

nahojkap
nahojkap

Reputation: 36

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.

Upvotes: 1

Related Questions