Nico Klasens <[EMAIL PROTECTED]> wrote:

> I don't see the difference between the 2 below in speed and I have no idea
> how to write it differently. The JVM has to do the same amount of method
> invocations. So what is bad in the first according to you?
>
>     private Calendar getCalendar() {
>         if (timezone != null) {
>             TimeZone tz = TimeZone.getTimeZone(timezone);
>             if (tz.getID().equals(timezone)) {
>                 return Calendar.getInstance(tz);
>             }
>             else {
>                 return Calendar.getInstance();
>             }
>         }
>         else {
>             return Calendar.getInstance();
>         }
>     }
>
>     private Calendar getCalendar() {
>         if (timezone != null) {
>             TimeZone tz = TimeZone.getTimeZone(timezone);
>             if (!tz.getID().equals(timezone)) {
>                 tz = TimeZone.getDefault();
>             }
>             return Calendar.getInstance(tz);
>         }
>         else {
>             return Calendar.getInstance();
>         }
>     }
>

That is what I did mean: there is no difference in speed, only in code. I
did not mean the code was bad.

I like to keep things straightforward and write:

    private static TimeZone getTimeZone(String timeZone) {
        if (timeZone == null || "".equals(timeZone.trim())) {
            return TimeZone.getDefault();
        } else {
            TimeZone tz = TimeZone.getTimeZone(timeZone);
            if (!tz.getID().equals(timeZone)) {
                tz = TimeZone.getDefault();
            }
            return tz;
        }
    }

private Calendar getCalendar() {
    return Calendar.getInstance(getTimeZone(timezone));
}

or even use Calendar.getInstance(getTimeZone(timezone)) everywhere without
an extra function. It would even better if the getTimeZone method in
DateFormat was public, then you did not need much code at all.

One remark: I believe there are timezones that can be set with several
different strings, so if you use (!tz.getID().equals(timeZone)) there will
be only one string that works. For the others you get the server timezone.

Martijn Houtman



Reply via email to