两个循环的性能差异.交换内外循环 [英] Two loops performance difference. Swapping inner and outer loop

查看:73
本文介绍了两个循环的性能差异.交换内外循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个循环(一个嵌套在另一个循环中),我想知道我嵌套这些循环的方式是否有任何不同.代码 1 和代码 2 的结果相同 (100,000x4 = 4x100,000 = 400,000) 但 jsPerf 显示代码2 大约比代码 1 快 50%.

I had two loops (one nested in the other one) and I was wondering if there is any difference in how I nest these loops. Results of Code 1 and Code 2 are the same (100,000x4 = 4x100,000 = 400,000) but jsPerf shows that Code 2 is roughly 50% faster than Code 1.

我想请教您的建议,我不明白两者之间的区别.

I'd like to kindly ask for your advice, I don't understand the difference between the two.

非常感谢.

var tt = function () {
      // do some stuff
      // for example:
      return (3);
    };

测试代码1:

for (var i = 0; i < 100000; i++) {
  for (var j = 0; j < 4; j++) {
    tt();
  }
}

测试代码 2:

for (var j = 0; j < 4; j++) {
  for (var i = 0; i < 100000; i++) {
    tt();
  }
}

推荐答案

区别在于循环初始化代码.第一个代码必须初始化内循环 100,000 次,而第二个代码只执行 4 次.

The difference is in the loop initialization code. The first code has to initialize the inner loop 100,000 times while the second one only does that 4 times.

这篇关于两个循环的性能差异.交换内外循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆