最近在做的軟體需要日誌功能,其中一項是顯示日期與時間。到網上搜了一圈,日期格式化函式滿街都是,但仔細看会发现:程式碼不夠優雅,效能也不理想。於是乾脆做一次量化實測。
對每個格式化函式做 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);
這是在中文社群流傳最廣的版本,用一個 map 收集各欄位值,再用正則逐一替換:
// 對 Date 的擴展,將 Date 轉化為指定格式的 String
// 月(M)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個占位符,
// 年(y)可以用 1-4 個占位符,毫秒(S)只能用 1 個占位符(是 1-3 位的數字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.format1 = function (fmt) { // author: meizz
var o = {
"M+" : this.getMonth() + 1, // 月份
"d+" : this.getDate(), // 日
"h+" : this.getHours(), // 小時
"m+" : this.getMinutes(), // 分
"s+" : this.getSeconds(), // 秒
"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
"S" : this.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
三次測試成績:6657 毫秒、6739 毫秒、6747 毫秒,平均約 6714 毫秒。
這個版本功能更豐富,支援 E(星期)、H(24 小時)與 h(12 小時)的區分:
Date.prototype.format2 = function (fmt) {
var o = {
"M+" : this.getMonth() + 1, // 月份
"d+" : this.getDate(), // 日
"h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 12 小時制
"H+" : this.getHours(), // 24 小時制
"m+" : this.getMinutes(), // 分
"s+" : this.getSeconds(), // 秒
"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
"S" : this.getMilliseconds() // 毫秒
};
var week = {
"0" : "日", "1" : "一", "2" : "二",
"3" : "三", "4" : "四", "5" : "五", "6" : "六"
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
三次測試成績:7334 毫秒、7497 毫秒、7498 毫秒,平均約 7443 毫秒。功能更多,代價也更高。
秉持完美主義,重新寫了一版。主要改動有三點:不再擴充 Date 原型,改為純函式;用單一正則的 replace 回呼一次掃完,取代迴圈中反覆 new RegExp;把 map 提到函式內建立,避免污染全域。
/**
* 對日期進行格式化
* @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)
* @return String
*/
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% 的時間,效能提升一倍以上。差異主要來自兩處:
for...in 迴圈中每次都 new RegExp("(" + k + ")"),50 萬次呼叫下就是數百萬次的動態編譯。新版只用一個字面值正則 /([yMdhmsqS])+/g,瀏覽器可以預先編譯並快取。RegExp.$1 這個全域狀態,而新版透過 replace 回呼的參數直接取得比對結果,省去狀態查詢。另外,從原型擴充改為靜態函式不只是風格問題。Date.prototype.format1 會讓所有 for...in 遍歷 Date 物件時多出一個屬性,某些老舊程式碼可能因此出錯;靜態函式則完全沒有這個副作用。
當然,這些數字是特定環境下的實測值,不同瀏覽器與機器會有差異。但「避免在熱迴圈中動態編譯正則」這個結論是通用的。