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

for循环执行的优化 #2

Open
2 tasks
IAIAE opened this issue Jun 14, 2020 · 1 comment
Open
2 tasks

for循环执行的优化 #2

IAIAE opened this issue Jun 14, 2020 · 1 comment

Comments

@IAIAE
Copy link
Owner

IAIAE commented Jun 14, 2020

for循环的原本执行流程如下:

for(let i=0;i<10;i++){
     const sum  = i;
}

1、创建scope,执行init
2、创建scope,执行body()
3、执行test()和update()

这样产生一个问题,虽然执行body之前创建了新的scope,保证了每次循环都在新的scope内执行。但是body内的closure并没有新创建,还是原来的,也就是说,每次循环,body内的scope都是同一个。如果遇到了const,就会报错,因为不能重复赋值。所以,正确的执行流程应该是:

0、实现写好getClosure方法。
1、创建scope,执行init
2、调用getClosure(),获取一个全新的body执行closure,然后再执行closure()。这样可以保证每次循环执行的body都是全新的。
3、执行test()和update()

但是这样明显加大了运行时的开销。一种好的办法是clone一份body中运行时的scope完全样本,每次循环开始在从样本clone一份出来重置body的scope。这样少了新建closure的开销。

所以任务是:

  • 修正for循环逻辑,保证每次循环body内部数据都是新的,保证程序正确执行结果
  • 优化,不要每次都创建closure,只更新scope
@IAIAE
Copy link
Owner Author

IAIAE commented Jun 14, 2020

  • 修正for循环逻辑,保证每次循环body内部数据都是新的,保证程序正确执行结果
  • 优化,不要每次都创建closure,只更新scope

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

No branches or pull requests

1 participant