In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article to share with you is about the measurement of JavaScript function performance simple methods and comparison with other ways, Xiaobian think quite practical, so share to everyone to learn, I hope you can read this article after some harvest, not much to say, follow Xiaobian to see it.
Measuring the time it takes to execute a function is always a good way to prove that some implementations perform better than another. This is also a good way to ensure that performance is not affected after certain changes and to track bottlenecks.
Good performance contributes to a good user experience, and a good user experience keeps users coming back. One study showed that 88% of online consumers are less likely to come back after a poor user experience because of performance issues.
This is why it is possible to identify bottlenecks in code and measure improvements. Especially when developing JavaScript for browsers, be aware that every line of JavaScript you write has the potential to block DOM because it is a single-threaded language.
Perfomance.now
The performance API provides access to DOMHighResTimeStamp through its function performance.now(), which returns the elapsed time since the page was loaded in milliseconds to an accuracy of up to 5µs in fractions.
So in practice, you need to take two timestamps, store them in a variable, and subtract the first from the second.
const t0 = performance.now(); for (let i = 0; i
< array.length; i++) { // some code } const t1 = performance.now(); console.log(t1 - t0, 'milliseconds'); Chrome输出 0.6350000001020817 "milliseconds" Firefox输出 1 milliseconds 在这里,我们可以看到Firefox中的结果与Chrome完全不同,这是因为Firefox版本从60开始将 performance API 的精度降低到2ms。 performance API提供的功能远比只返回时间戳要多得多,它能够测量导航计时、用户计时或资源计时。请看这篇文章,里面有更详细的解释。 但是,对于我们的用例,我们只想测量单个函数的性能,因此时间戳就足够了。 那不是和Date.now一样吗? 现在你可能会想:我也可以用 Date.now 来做这个啊。 是的,可以,但是有缺点。 Date.now 以毫秒为单位返回从Unix纪元("1970-01-01-01T00:00:00:00Z")开始的时间,并且取决于系统时钟。这不仅意味着它没有那么精确,而且也不一定会递增。WebKit工程师(Tony Gentilcore)的解释如下: 也许较少考虑到的是,基于系统时间的Date也不是真正的用户监控的理想选择。大多数系统都会运行一个守护进程来定期同步时间。通常情况下,时钟每隔15-20分钟就会调整几毫秒。在这个速度下,大约有1%的10秒的时间间隔是不准确的。 Console.time 该API确实易于使用,只需将 console.time 放在你要测量的代码前面,将 console.timeEnd 放在要测量的代码后面,即可使用相同的 string 参数调用该函数,一页上最多可以同时使用10,000个计时器。 精度与 performance API 相同,但这又取决于浏览器。 console.time('test'); for (let i = 0; i < array.length; i++) { // some code } console.timeEnd('test'); 这样会自动生成易于理解的输出,如下所示: Chrome输出 test: 0.766845703125ms Firefox输出 test: 2ms - timer ended 这里的输出又与Performance API非常相似。 console.time 的优点是易于使用,因为它不需要手动计算两个时间戳之间的差。 缩短时间精度 如果你在不同的浏览器中使用上面提到的API来测量你的函数,你可能会发现结果会有差异。 这是由于浏览器试图保护用户免受定时攻击和指纹攻击, 如果时间戳太准确,黑客可以使用它来识别用户。 例如,Firefox之类的浏览器试图通过将精度降低到2ms(版本60)来防止这种情况。 需要注意的事项 现在,你已经拥有测量JavaScript函数的速度所需的工具。但是,最好避免一些陷阱。 1. 分而治之 你注意到在过滤一些结果时有些东西很慢,但是你不知道瓶颈在哪里。 与其胡乱猜测代码中哪一部分是慢的,不如用上述这些函数来测量。 要追踪它,首先把你的 console.time 语句放在慢的代码块周围。然后测量它们的不同部分是如何执行的,如果其中一个部分比其他部分慢,那么就继续下去,每次深入到那里,直到找到瓶颈。 这些语句之间的代码越少,跟踪不感兴趣的内容的可能性就越小。 2. 注意输入值 在实际应用中,给定函数的输入值可能会发生很大变化。仅针对任意随机值测量函数的速度并不能提供我们可以实际使用的任何有价值的数据。 确保使用相同的输入值运行代码。 3. 多次运行函数 假设你有一个函数对一个数组进行迭代,对每个数组的值进行一些计算,并返回一个数组的结果。你想知道是forEach 还是简单的 for 循环更有效。 这是函数: function testForEach(x) { console.time('test-forEach'); const res = []; x.forEach((value, index) =>{ res.push(value / 1.2 * 0.1); }); console.timeEnd('test-forEach') return res; } function testFor(x) { console.time('test-for'); const res = []; for (let i = 0; i
< x.length; i ++) { res.push(x[i] / 1.2 * 0.1); } console.timeEnd('test-for') return res; } 你可以这样测试它们: const x = new Array(100000).fill(Math.random()); testForEach(x); testFor(x); 如果你在Firefox中运行上述函数,你将获得类似以下的输出: test-forEach: 27ms - timer ended test-for: 3ms - timer ended 看起来forEach变慢了,对吧? 让我们看看是否使用相同的输入两次运行相同的函数: testForEach(x); testForEach(x); testFor(x); testFor(x);test-forEach: 13ms - timer ended test-forEach: 2ms - timer ended test-for: 1ms - timer ended test-for: 3ms - timer ended 如果我们第二次调用 forEach 测试,它的性能与 for 循环一样好。鉴于初始值较慢,可能无论如何都不值得使用 forEach。4. ... in multiple browsers
If we run the above code in Chrome, the result suddenly looks different:
test-forEach: 6.156005859375ms test-forEach: 8.01416015625ms test-for: 4.371337890625ms test-for: 4.31298828125ms
This is because Chrome and Firefox have different JavaScript engines and have different types of performance optimizations. Being aware of these differences is a good thing.
In this case, Firefox optimizes the use of forEach for the same input.
For performs better on both engines, so it's best to stick with the for loop.
This is a good example of why measurements are made in multiple engines. If you measure with Chrome alone, you might conclude that forEach isn't that bad compared to for-for.
5. Throttle your CPU
These numbers don't seem high. Keep in mind that your development machine is usually much faster than the average mobile phone you use for your website.
To get a feel for this, browsers have a feature that lets you throttle your CPU performance.
With this, those 10 or 50ms quickly became 500 ms.
6. Measure relative performance
These raw results actually depend not only on your hardware, but also on your CPU and the current load of your JavaScript threads. Try to keep an eye on the relative improvement in your measurements, because the numbers may look very different the next time you restart your computer.
We saw some JavaScript APIs that we could use to measure performance and how to use them in the "real world." For simple measurements, I find it easier to use console.time.
The above is a simple way to measure the performance of JavaScript functions and compare it with other ways. Xiaobian believes that some knowledge points may be seen or used in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.