在高頻日誌記錄、實時儀表盤等場景中,日期格式化函數的性能直接影響前端響應速度。本文對網上流傳的幾種常見 Date.prototype.format 實現進行 50 萬次基準測試,分析性能差異並給出優化建議。
測試代碼結構統一,對單一格式化函數執行 500,000 次循環,記錄總耗時(毫秒):
var start = new Date().getTime();
var date = new Date();
for(var i = 0; i < 500000; i++){
date.format('yyyy-MM-dd hh:mm:ss');
}
console.log(new Date().getTime() - start);
Date.prototype.format1 = function (fmt) {
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;
};
測試結果(3 次平均):6,714 ms
代碼結構類似,但擴展了更多佔位符(H、E 等),邏輯判斷更多,導致性能略有下降。(完整代碼因篇幅省略)
test/replace。replace 產生大量中間字符串。formatDate(date, fmt),減少原型鏈查找,便於 Tree-shaking。date-fns、dayjs 或 luxon 等成熟庫,其內部高度優化且支援 Tree-shaking,體積極小。const TOKENS = {
'yyyy': d => d.getFullYear(),
'MM': d => String(d.getMonth() + 1).padStart(2, '0'),
'dd': d => String(d.getDate()).padStart(2, '0'),
'HH': d => String(d.getHours()).padStart(2, '0'),
'mm': d => String(d.getMinutes()).padStart(2, '0'),
'ss': d => String(d.getSeconds()).padStart(2, '0'),
'SSS': d => String(d.getMilliseconds()).padStart(3, '0')
};
function formatDate(date, fmt = 'yyyy-MM-dd HH:mm:ss') {
return fmt.replace(/yyyy|MM|dd|HH|mm|ss|SSS/g, match => TOKENS[match] ? TOKENS[match](date) : match);
}
// 測試:50萬次約 120ms(現代瀏覽器),較原版提升 50 倍以上
總結:早期經典代碼雖功能完整,但在高頻場景下性能不足。現代開發應優先選用成熟庫或採用預編譯 Token 映射的輕量實現。