@performance/reuse-date-instances-check
用于检测在循环或调用频繁的方法中重复创建Date对象,建议开发者重用现有实例或使用时间戳进行计算,减少创建Date成本。
规则配置
// code-linter.json5
{
"rules": {
"@performance/reuse-date-instances-check": "warn",
}
}
选项
该规则无需配置额外选项。
正例
aboutToAppear(): void {
// 记录开始时间戳
this.startTime = Date.now();
this.intervalId = setInterval(() => {
// 只获取时间戳,避免创建Date对象
const nowTimestamp = Date.now();
// 重用格式化结果
const currentTimeFormatted = this.formatElapsedTime(nowTimestamp);
this.currentTimeDisplay = currentTimeFormatted;
// 直接使用时间戳计算
const elapsedMs = nowTimestamp - this.startTime;
this.elapsedTimeDisplay = this.formatElapsedTime(elapsedMs);
// 添加到历史记录
const seconds = Math.floor(nowTimestamp / 1000) % 60;
if (seconds % 10 === 0) {
// 每十秒记录一次
this.elapsedTimes.push(`${this.elapsedTimeDisplay}-${currentTimeFormatted}`);
}
}, 1000);
}
反例
aboutToAppear(): void {
// 记录开始时间
this.startTime = Date.now();
// 问题:每秒创建多个Date对象
this.intervalId = setInterval(() => {
// 创建新Date对象显示当前时间
const now = new Date();
this.currentTimeDisplay = now.toLocaleTimeString();
// 再次创建Date对象计算持续时间
const currentDate = new Date();
const elapsedMs = currentDate.getTime() - this.startTime;
// 再次创建Date对象格式化持续时间
const elapsedDate = new Date(elapsedMs);
const hours = elapsedDate.getUTCHours();
const minutes = elapsedDate.getUTCMinutes();
const seconds = elapsedDate.getUTCSeconds();
const elapsedFormatted = `${hours.toString().padStart(2, '0')}:${
minutes.toString().padStart(2, '0')}:${
seconds.toString().padStart(2, '0')}`;
// 添加到历史记录
if (seconds % 10 === 0) {
// 每十秒记录一次
this.elapsedTimes.push(`${elapsedFormatted}-${new Date().toLocaleString()}`);
}
}, 1000);
}
规则集
plugin:@performance/recommended
plugin:@performance/all
Code Linter代码检查规则的配置指导请参考Code Linter代码检查。