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

不同条件下的each编译与优化 #108

Open
xinglie opened this issue Jul 5, 2023 · 0 comments
Open

不同条件下的each编译与优化 #108

xinglie opened this issue Jul 5, 2023 · 0 comments

Comments

@xinglie
Copy link
Owner

xinglie commented Jul 5, 2023

普通循环

{{each list as item}}
    {{=item}}
{{/each}}

编译为

for (let $q_c_b657119637f = list?.length, $q_key_1bca60b38e3 = 0; $q_key_1bca60b38e3 < $q_c_b657119637f; $q_key_1bca60b38e3 += 1) {
    let item = list[$q_key_1bca60b38e3];
    $vnode_0.push($createVNode(0, (item)));
}

当为倒序循环时

{{each list as item by desc}}
    {{=item}}
{{/each}}

编译为

for (let $q_key_4247bbc66bbb = list?.length; $q_key_4247bbc66bbb--;) {
    let item = list[$q_key_4247bbc66bbb];
    $vnode_0.push($createVNode(0, (item)));
} 

可以看到是使用

for(let index=list.length;index--;){

}

进行的优化

指定步长

{{each list as item step 2}}
    {{=item}}
{{/each}}

编译为

for (let $q_c_468888d338c0 = list?.length, $q_key_20dc8c0bb820 = 0; $q_key_20dc8c0bb820 < $q_c_468888d338c0; $q_key_20dc8c0bb820 += 2) {
    let item = list[$q_key_20dc8c0bb820];
    $vnode_0.push($createVNode(0, (item)));
} 

当为倒序循环时

{{each list as item step 2 by desc}}
    {{=item}}
{{/each}}

编译为

for (let $q_key_22aae5366430 = list?.length - 1; $q_key_22aae5366430 >= 0; $q_key_22aae5366430 -= 2) {
    let item = list[$q_key_22aae5366430];
    $vnode_0.push($createVNode(0, (item)));
}

当指定步长时,就需要考虑循环出边界的情况

循环深层对象

{{each user.address as item by desc}}
    {{=item}}
{{/each}}

编译为

for (let $q_a_60809231873f = user.address, $q_key_532b3fbca764 = $q_a_60809231873f?.length; $q_key_532b3fbca764--;) {
    let item = $q_a_60809231873f[$q_key_532b3fbca764];
    $vnode_0.push($createVNode(0, (item)));
} 

可以看到使用short=long.expr进行赋值操作,减少对象的深层次访问

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