Description
Describe the bug
Today I encountered a problem. I suddenly found that swc compression code was very slow. After investigation, I found that it was caused by the following code.
When minify.compress is enabled, swc will merge "a" + "b"
into "ab"
, but if a is a variable, it will be repeated many times, which will cause it to be very slow. And after exceeding a certain threshold, memory overflows.
For example, in my example, the variable is in the current scope and does not need to be merged. It seems that this compression cooperation operation can be skipped?
// build.js
import {transformSync} from "@swc/core";
function genCode(len) {
return `
export function add(a) {
return ${'a + "hello swc, minify" + '.repeat(len)} 'c'
}
`;
}
function minifyLen(len, fn) {
try {
const start = Date.now();
const code = fn(len);
transformSync(code, {
jsc: {
parser: {
syntax: "ecmascript",
},
transform: {},
minify: {
mangle: true,
compress: true,
},
},
minify: true,
});
console.log(fn.name, len, 'cost:', Date.now() - start, 'ms');
} catch (e) {
console.log(fn.name, len, 'error:', e);
}
}
minifyLen(100, genCode)
minifyLen(1000, genCode)
minifyLen(2000, genCode)
minifyLen(3000, genCode)
case1: ${'a + "hello swc, minify" + '.repeat(len)} 'c'
genCode 100 cost: 113 ms
genCode 1000 cost: 222 ms
genCode 2000 cost: 1019 ms
[1] 57128 segmentation fault node ./build.js
case2: ${'"a" + "hello swc, minify" + '.repeat(len)} 'c'
genCode2 100 cost: 94 ms
genCode2 1000 cost: 6 ms
genCode2 2000 cost: 18 ms
[1] 57423 segmentation fault node ./build2.js
case3: ${'a + b + '.repeat(len)} c;
genCode3 100 cost: 10 ms
genCode3 1000 cost: 148 ms
genCode3 2000 cost: 638 ms
[1] 57461 segmentation fault node ./build3.js
Input code
Config
Playground link (or link to the minimal reproduction)
https://github.com/noyobo/swc-issues/tree/swc-minify
SWC Info output
Operating System:
Platform: darwin
Arch: x64
Machine Type: x86_64
Version: Darwin Kernel Version 23.1.0: Mon Oct 9 21:27:27 PDT 2023; root:xnu-10002.41.9~6/RELEASE_X86_64
CPU: (12 cores)
Models: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
Binaries:
Node: 20.12.0
npm: 10.5.0
Yarn: 1.22.22
pnpm: 9.4.0
Relevant Packages:
@swc/core: 1.11.10
@swc/helpers: N/A
@swc/types: N/A
SWC Config:
output: N/A
.swcrc path: N/A
Next.js info:
output: N/A
Expected behavior
Compress code fast
Actual behavior
No response
Version
1.11.10
Additional context
No response