You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript是否支持更简洁的性能测试专用语法?

问题

我需要跟踪多个流程的耗时,当前代码写法如下:

console.log("Doing thing 1");
var startTime = performance.now();
var thing = doThing()
times.loadTime = performance.now() - startTime;

console.log("Doing thing 2");
startTime = performance.now();
var thing2 = doOtherThing();
var endTime = performance.now();
times.thingTime2 = endTime - startTime;

console.log("Doing thing 3");
var thing3 = doThing3();
ties.thingTime3 = performance.now() - endTime;

这种写法的可读性越来越差。我知道当前环境可使用如下方法:

console.startTime();
console.startTime("Thing 1");
console.endTime();

详情可查看console对象。但我曾见过JavaScript代码使用类似块或标签的写法:

thing1 {
   var thing = doThing()
}

thing2 {
    var thing2 = doOtherThing();
}

thing3 {
    var thing3 = doThing3();
}

// desired result { name: "thing1", startTime: 0, endTime: 10 }
console.log(thing1);

或是标签形式:

thing1:
    var thing = doThing()
end

这类写法的可读性更强,请问JavaScript是否支持这种写法?

回答

JavaScript原生并不支持你展示的这两种自定义块/标签写法,它们都不属于标准语法:

  • 第一种thing1 { ... }的写法会被JS引擎判定为语法错误——如果thing1不是已定义的函数,这种写法不符合任何JS语法规则;就算thing1是函数,正确调用也得是thing1(() => { ... })这类形式。
  • 第二种thing1:加end的写法,JS里确实存在标签语句,比如thing1:可以用来标记循环或代码块,但end不是JS的关键字,这种写法同样会报错。标签语句的常规用法是配合break/continue跳出嵌套循环,比如:
outerLoop:
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    if (j === 3) break outerLoop;
    console.log(i, j);
  }
}

但它无法实现你想要的自动计时并返回耗时数据的功能。

不过你可以自己封装一个简单的计时函数,模拟这种高可读性的写法,完全符合JS标准语法:

const timers = {};

function timeBlock(name, callback) {
  const startTime = performance.now();
  const result = callback();
  const endTime = performance.now();
  timers[name] = {
    name,
    startTime,
    endTime,
    duration: endTime - startTime
  };
  return result;
}

// 使用方式
const thing = timeBlock('thing1', () => doThing());
const thing2 = timeBlock('thing2', () => doOtherThing());
const thing3 = timeBlock('thing3', () => doThing3());

// 查看计时结果
console.log(timers.thing1);

另外你提到的console.time()/console.timeEnd()也是浏览器环境下的原生方案,适合快速调试,它会直接在控制台输出耗时:

console.time('thing1');
const thing = doThing();
console.timeEnd('thing1'); // 控制台会输出 "thing1: XXX ms"

内容的提问来源于stack exchange,提问作者1.21 gigawatts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:15:57