Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 13题(2019-08-7):为什么for循环嵌套顺序会影响性能? #7

Open
qappleh opened this issue Aug 7, 2019 · 1 comment

Comments

@qappleh
Copy link
Owner

qappleh commented Aug 7, 2019

var t1 = new Date().getTime()
for (let i = 0; i < 100; i++) {
  for (let j = 0; j < 1000; j++) {
    for (let k = 0; k < 10000; k++) {
    }
  }
}
var t2 = new Date().getTime()
console.log('first time', t2 - t1)

for (let i = 0; i < 10000; i++) {
  for (let j = 0; j < 1000; j++) {
    for (let k = 0; k < 100; k++) {

    }
  }
}
var t3 = new Date().getTime()
console.log('two time', t3 - t2)  
@qappleh
Copy link
Owner Author

qappleh commented Aug 8, 2019

两个循环的次数的是一样的,但是 j 与 k 的初始化次数是不一样的

第一个循环的 j 的初始化次数是 100 次,k 的初始化次数是 10w 次
第二个循环的 j 的初始化次数是 1w 次, k 的初始化次数是 1000w 次
所以相同循环次数,外层越大,越影响性能

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant