通过将表达式移动到' if '条件子句,uglifyjs获得了什么?

What does uglifyjs gain by moving expressions to the `if` condition clause?

本文关键字:子句 uglifyjs 获得了 什么 条件 if 移动 表达式      更新时间:2023-09-26

以下代码

console.log("foo");
if (window.x !== window.y) {
    const x = "x";
    console.log(x);
}
使用uglifyjs将

缩小为

if(console.log("foo"),window.x!==window.y){const x="x";console.log(x)}

可以看出它并不比

更直接
console.log("foo");if(window.x!==window.y){const x="x";console.log(x)}

那么他们通过移动它得到了什么?这是一些棘手的引擎特定的优化还是有一个原因,我不能看到?

正如@GOTO指出的那样,第二个变体可能是相同的长度,gzip后会更长:

$ echo 'if(console.log("foo"),window.x!==window.y){const x="x";console.log(x)}' | gzip | wc --bytes
74
$ echo 'console.log("foo");if(window.x!==window.y){const x="x";console.log(x)}' | gzip | wc --bytes
76

有人在他们的自述文件中给我指了一个地方,在那里他们做了说明

块中的

连续语句合并成一个序列;在许多情况下,这使得块只剩下一条语句,因此我们可以删除块括号。

所以这里不是这样,但是当你有像

这样的东西时,它会节省2个字符
if (<expr>) {
    console.log("foo");
    if (window.x !== window.y) {
        const x = "x";
        console.log(x);
    }
}