CPU周期,内存使用情况,执行时间等等?

除了感知代码的运行速度之外,是否有一种量化的方法来测试JavaScript的性能?


当前回答

你可以使用控制台。firebug中的配置文件

其他回答

我通常只测试javascript的性能,脚本运行多长时间。jQuery Lover提供了一个很好的测试javascript代码性能的文章链接,但这篇文章只展示了如何测试javascript代码运行多长时间。我还推荐阅读一篇文章,题为“在处理大量数据集时改进jQuery代码的5个技巧”。

黄金法则是在任何情况下都不要锁定用户的浏览器。在此之后,我通常会查看执行时间,然后是内存使用情况(除非您正在做一些疯狂的事情,在这种情况下,内存使用的优先级可能更高)。

这是为特定操作收集性能信息的好方法。

start = new Date().getTime(); 
for (var n = 0; n < maxCount; n++) {
/* perform the operation to be measured *//
}
elapsed = new Date().getTime() - start;
assert(true,"Measured time: " + elapsed);

这是一个非常老的问题,但我认为我们可以提供一个基于es6的简单解决方案来快速测试你的代码。

这是用于执行时间的基本工作台。我们使用performance.now()来提高精度:

/** * Figure out how long it takes for a method to execute. * * @param {Function} method to test * @param {number} iterations number of executions. * @param {Array} list of set of args to pass in. * @param {T} context the context to call the method in. * @return {number} the time it took, in milliseconds to execute. */ const bench = (method, list, iterations, context) => { let start = 0 const timer = action => { const time = performance.now() switch (action) { case 'start': start = time return 0 case 'stop': const elapsed = time - start start = 0 return elapsed default: return time - start } }; const result = [] timer('start') list = [...list] for (let i = 0; i < iterations; i++) { for (const args of list) { result.push(method.apply(context, args)) } } const elapsed = timer('stop') console.log(`Called method [${method.name}] Mean: ${elapsed / iterations} Exec. time: ${elapsed}`) return elapsed } const fnc = () => {} const isFunction = (f) => f && f instanceof Function const isFunctionFaster = (f) => f && 'function' === typeof f class A {} function basicFnc(){} async function asyncFnc(){} const arrowFnc = ()=> {} const arrowRFnc = ()=> 1 // Not functions const obj = {} const arr = [] const str = 'function' const bol = true const num = 1 const a = new A() const list = [ [isFunction], [basicFnc], [arrowFnc], [arrowRFnc], [asyncFnc], [Array], [Date], [Object], [Number], [String], [Symbol], [A], [obj], [arr], [str], [bol], [num], [a], [null], [undefined], ] const e1 = bench(isFunction, list, 10000) const e2 = bench(isFunctionFaster, list, 10000) const rate = e2/e1 const percent = Math.abs(1 - rate)*100 console.log(`[isFunctionFaster] is ${(percent).toFixed(2)}% ${rate < 1 ? 'faster' : 'slower'} than [isFunction]`)

性能测试最近成了一个流行词,但这并不是说性能测试在QA中不是一个重要的过程,甚至在产品发布之后也不是。当我开发应用程序时,我使用了许多不同的工具,其中一些是上面提到的chrome Profiler,我通常会查看一个SaaS或一些开源的东西,我可以开始工作,然后忘记它,直到我收到警告,说有些东西出了问题。

有很多很棒的工具可以帮助您关注性能,而不需要您跳过一些基本的提醒设置。这里有一些我认为值得你自己去看看。

Sematext.com Datadog.com Uptime.com Smartbear.com Solarwinds.com

为了画出更清晰的画面,这里有一个关于如何为react应用程序设置监控的小教程。