Daan
Daan

Reputation: 1437

Javascript: which 'time processing' function is faster?

I just created two versions of a function that can be used to process the date and time and return it to different HTML elements. These elements will be displayed a phone lockscreen. The function is called every second, to make sure it jumps to the next minute in time.

I'd expected v.2 to be faster, but according to a test I did here: http://jsperf.com/timecalccompare it's about 90% slower! Is it really slower or is the test unreliable?

Upvotes: 1

Views: 99

Answers (3)

Albert Tsang
Albert Tsang

Reputation: 53

advise:try to reduce the number of DOM access

your step by step script is not working!

Upvotes: 0

AKX
AKX

Reputation: 168913

I'd go with the simpler way, but additionally check if the minute has actually changed before updating the view and doing the rest of the calculations:

Also there's absolutely no reason to declare the months and days array on each iteration, so:

var months      = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var days        = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

var lastMinute = null;

function Update()
{
    var now, minutes, hours, day, date, month, daypart = "AM";
    now         = new Date();
    minutes     = now.getMinutes();
    if(minutes == lastMinute) return;
    hours       = now.getHours();
    day         = days[now.getDay()];
    date        = now.getDate();
    month       = months[now.getMonth()].substring(0, 3);

    if(minutes < 10) minutes = "0" + minutes;
    if(hours > 12) {
        hours -= 12;
        daypart = "PM";
    }
    if(hours == 0) hours = 12;

    $("#clock").text(hours + ":" + minutes + " " + daypart);
    $("#day").text(day);
    $("#date").text(date + " " + month);
    lastMinute = minutes;
}

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182763

Your second version is just broken and doesn't do anything remotely approaching what it's supposed to do. If incrementing the seconds doesn't leave them at zero, you need to stop processing, not keep doing a bunch more tests.

Upvotes: 0

Related Questions