近期開發的軟體需要日誌功能,其中顯示日期與時間是相當重要的一環。上網搜尋後發現日期格式化函數雖然很多,但普遍不夠優雅,效能也不理想,於是乾脆自己做了一場評測。
對每個格式化函數各執行 50 萬次計算,記錄耗時:
var start = new Date().getTime();
var date = new Date();
for (var i = 0; i < 500000; i++) {
date.format1('yyyy-MM-dd hh:mm:ss');
}
console.log(new Date().getTime() - start);
這是最廣為流傳的經典寫法,透過正則表達式逐一替換各個時間欄位。三次測試成績分別為 6657、6739、6747 毫秒,平均約 6714 毫秒。
在函數一的基礎上擴充了星期(E)與 12 小時制(h)、24 小時制(H)的表示。三次測試成績為 7334、7497、7498 毫秒,平均約 7443 毫秒,反而略慢一些。
本著完美主義,我重新打造了一個更高效的版本,改採靜態函數、以單次正則替換完成所有欄位:
/**
* 對日期進行格式化
* @param date 要格式化的日期
* @param format 格式化的模式字串
* 支援:y年、M月(1-12)、d日(1-31)、h時(0-23)、m分(0-59)、s秒(0-59)、S毫秒(0-999)、q季度(1-4)
*/
function dateFormat(date, format) {
if (format === undefined) {
format = date;
date = new Date();
}
var map = {
"M": date.getMonth() + 1,
"d": date.getDate(),
"h": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"q": Math.floor((date.getMonth() + 3) / 3),
"S": date.getMilliseconds()
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t){
var v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
}
// 使用方式
dateFormat('yyyy-MM-dd hh:mm:ss');
dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss');
三次測試成績為 2903、2900、2896 毫秒,平均約 2899 毫秒。
對比之下,效能從原本的平均 6714 毫秒大幅降到 2899 毫秒,整整少了 3815 毫秒,相當於只需原本 43% 的時間,效能提升超過一倍。而且從「擴充原型」改為「靜態函數」的呼叫方式,也更為優雅清晰。