简体   繁体   中英

Android Wear: Is there any reason to use a Time object rather than a Calendar object?

Here's what I know, if there's any errors, let me know.

Example watch faces, like the analog watch face , in the SDK use a deprecated Time object for managing time.

According to the documentation Time was deprecated in level 22 (Android 5.1). Now obviously it still has a lot of life, but in the interests of future proofing code I looked I looked at switching to the Calendar object.

I believe both Time and Calendar are fancy wrappers for a long variable. I wrote this benchmark to test their speed.

            long timeStart = 0;
            long timeEndcalendarStart = 0;
            long timeDifference = 0;
            long calendarEnd = 0;
            long calendarDifference = 0;


            for (int index = 0; index < 30000; index++) {

                timeStart = System.currentTimeMillis();
                Time testTime = new Time();
                testTime.setToNow();
                long mills = testTime.toMillis(false);
                float seconds = testTime.second;
                float minutes = testTime.minute;
                float hours = testTime.hour;

                timeEndcalendarStart = System.currentTimeMillis();

                Calendar testCalendar = Calendar.getInstance();
                long cmills = testCalendar.getTimeInMillis();
                float cseconds = testCalendar.get(Calendar.SECOND);
                float cminutes = testCalendar.get(Calendar.MINUTE);
                float chours = testCalendar.get(Calendar.HOUR);
                calendarEnd = System.currentTimeMillis();

                timeDifference += timeEndcalendarStart - timeStart;
                calendarDifference += calendarEnd - timeEndcalendarStart;
            }

The benchmark results show Calendar as 2x faster running it on a Moto 360.

Switching a test watch face to Calendar shows no memory being leaked in the debugger.

So my question is two fold. Is there a problem with my benchmark, or is it indeed faster? If so, what is the advantage of Time, such that they used it in their examples?

My hypothesis is that they just used it to make their examples more understandable. Time is a more intuitive name, but I'd like to know if there's a technical reason.

When the samples were written, the Time class wasn't deprecated yet. We would use Calendar if we wrote them now. Use Calendar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM