JS代码压缩实测:可减小体积、提高执行效率!

你知道吗?

JS压缩,可以有效减小代码体积、提高代码执行效率!

具体压缩率有多高?能提升多少执行效率呢?

本文用实测的方式给出答案。

一、JS压缩工具

这里使用的是JShaman的JS代码压缩,是一款在线使用的JS压缩工具,如下图:

二、如何使用?

该工具使用很简单:输入JS代码、执行压缩、得到压缩后的JS代码。

有配置选项,一般用默认就可以了,如下图:

三、实测压缩效果

下 面,通过几个实例,测试压缩率、执行效率。

测试1

JS代码:

javascript 复制代码
//1、去除未使用的函数、变量
var var_one = 1;
var var_two = 2;
function fun_one(){
    var function_one_var_one;
    console.log(var_one);
}
function fun_two(){
    console.log(var_one);
}
fun_one();
{
    function fun_three(){
        console.log("function three");
    }
}
//2、去除空行代码
;;;

//3、优化if、三元运算
if(1==1){
    console.log("1=1");
} else {
    console.log("1!=1");
}
2==2?console.log("2=2"):console.log("2!=2");

//4、变量使用转化为字符串直接引用
var four_one = 4;
var four_two;
var four_three ="this is four_three";
four_two = 5;
console.log(four_one,four_two,four_three,four_three);

//5、字符串拼接
var five_one = 1 + 2 + 3;
var five_two = "I am " + "a " + "bird";
console.log(five_one,five_two);

压缩:

压缩后的代码:

javascript 复制代码
var var_one=1;var var_two=2;function fun_one(){console.log(var_one);}function fun_two(){console.log(var_one);}fun_one();{}console.log("1=1");console.log("2=2");var four_two;var four_three="this is four_three";four_two=5;console.log(4,four_two,four_three,four_three);var five_one=6;var five_two="I am a bird";console.log(five_one,five_two);

压缩效果:

代码体积减小:49.70%

代码综合性能提升约:6.2%,解析速度提升约:14.6%,运行速度提升约:2.6%

erlang 复制代码
压缩前体积:0.66 KB
压缩后体积:0.33 KB
代码体积减小:49.70%

代码共压缩11处,明细:

去除未使用的局部函数 1 个
去除未使用的局部变量 1 个
去除空行、无效符号 3 个
简化if语句或三元运算 2 个
常量替换为直接引用 2 个
字符串拼接优化 2 个

代码综合性能提升约:6.2%,解析速度提升约:14.6%,运行速度提升约:2.6%

测试2

JS代码:

javascript 复制代码
(function (){
    var domain = "jshaman";
    var from_year = 2017;
    var copyright = function(){
        return "(c)" + from_year + "-" + (new Date).getFullYear() + "," + domain;
    };
    var console_log = console.log;
    console_log(copyright())
})();

压缩后的JS代码:

javascript 复制代码
(function(){var _c=function(){return"(c)2017-"+new Date().getFullYear()+","+"jshaman";};var _c2=console.log;_c2(_c());})();

压缩效果:

代码体积减小:52.51%

代码综合性能提升约:4.3%,解析速度提升约:13.5%,运行速度提升约:0.3%

erlang 复制代码
压缩前体积:0.25 KB
压缩后体积:0.12 KB
代码体积减小:52.51%

代码共压缩5处,明细:

常量替换为直接引用 2 个
字符串拼接优化 1 个
局部变量名缩短 2 个

代码综合性能提升约:4.3%,解析速度提升约:13.5%,运行速度提升约:0.3%

测试3

用AI写一段代码:

JS代码:

javascript 复制代码
// ============================================================
//  JS代码压缩测试Demo - 包含多种语法结构与复杂逻辑
// ============================================================

// ---------- 1. 对象、数组、解构、模板字符串 ----------
const config = {
  name: 'CompressionDemo',
  version: '1.0.0',
  debug: true,
  features: ['minify', 'mangle', 'deadCode'],
};

const { name, version, features } = config;

// ---------- 2. 复杂函数:闭包、默认参数、箭头函数、展开运算符 ----------
function createCalculator(initialValue = 0) {
  let value = initialValue;

  return {
    add: (step = 1) => {
      value += step;
      return value;
    },
    subtract: (step = 1) => {
      value -= step;
      return value;
    },
    multiply: (factor) => {
      value *= factor;
      return value;
    },
    getValue: () => value,
    reset: () => {
      value = initialValue;
      return value;
    },
  };
}

// ---------- 3. 类与继承、静态方法、getter/setter ----------
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
    this._secret = 'classified';
  }

  get info() {
    return `${this.name} (${this.age} years old)`;
  }

  set secret(value) {
    if (typeof value === 'string' && value.length > 0) {
      this._secret = value;
    }
  }

  static compareAge(a, b) {
    return a.age - b.age;
  }
}

class Dog extends Animal {
  constructor(name, age, breed) {
    super(name, age);
    this.breed = breed;
  }

  bark() {
    console.log(`Woof! I'm ${this.name}`);
  }

  get info() {
    return `${super.info}, breed: ${this.breed}`;
  }
}

// ---------- 4. 异步函数、Promise、setTimeout ----------
function fetchData(flag) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (flag) {
        resolve({ data: 'sample data', status: 'success' });
      } else {
        reject(new Error('Invalid flag'));
      }
    }, 100);
  });
}

async function processData() {
  try {
    const result = await fetchData(true);
    console.log('Fetched:', result);
    return result;
  } catch (error) {
    console.error('Error:', error.message);
    return null;
  }
}

// ---------- 5. 高阶函数、数组方法链 ----------
const numbers = [5, 12, 8, 130, 44, 2, 99, 3];

const processed = numbers
  .filter((n) => n % 2 === 0)
  .map((n) => n * 2)
  .sort((a, b) => a - b)
  .reduce((acc, n) => acc + n, 0);

// ---------- 6. 条件逻辑、三元运算符、短路求值 ----------
function getStatus(score) {
  if (score >= 90) return 'A';
  if (score >= 80) return 'B';
  if (score >= 70) return 'C';
  if (score >= 60) return 'D';
  return 'F';
}

const status = getStatus(85);
const message = status === 'A' ? 'Excellent!' :
                status === 'B' ? 'Good job!' :
                status === 'C' ? 'Keep trying' :
                'Needs improvement';

// ---------- 7. 循环(for、for...of、forEach) ----------
function sumArray(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  return sum;
}

function printItems(items) {
  for (const item of items) {
    console.log(item);
  }
}

function doubleValues(arr) {
  const result = [];
  arr.forEach((val, idx) => {
    result.push(val * 2 + idx);
  });
  return result;
}

// ---------- 8. 立即执行函数(IIFE) ----------
const counter = (function() {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
    getCount: () => count,
  };
})();

// ---------- 9. 对象属性简写、计算属性名 ----------
const key = 'dynamicKey';
const obj = {
  key,
  [key]: 'dynamicValue',
  method() {
    return this.key;
  },
};

// ---------- 10. 工具函数(防抖、节流) ----------
const utils = {
  debounce(fn, delay = 300) {
    let timer = null;
    return function(...args) {
      clearTimeout(timer);
      timer = setTimeout(() => fn.apply(this, args), delay);
    };
  },
  throttle(fn, limit = 200) {
    let inThrottle = false;
    return function(...args) {
      if (!inThrottle) {
        fn.apply(this, args);
        inThrottle = true;
        setTimeout(() => (inThrottle = false), limit);
      }
    };
  },
};

// ---------- 11. 死代码/未使用变量(测试压缩工具优化) ----------
const UNUSED_CONST = 'This is never used';
function unusedFunction() {
  return 'I am dead code';
}
var unusedVar = 42;

// ---------- 12. 导出(模拟模块) ----------
// ES Module风格(注释掉,根据需要启用)
// export {
//   createCalculator,
//   Animal,
//   Dog,
//   processData,
//   processed,
//   status,
//   message,
//   counter,
//   utils,
// };

// CommonJS风格(Node.js)
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    createCalculator,
    Animal,
    Dog,
    processData,
    processed,
    status,
    message,
    counter,
    utils,
  };
}

// ---------- 13. 实际执行代码,防止被完全Tree Shaking ----------
console.log('=== Compression Demo Output ===');
const calc = createCalculator(10);
console.log('calc.add(5):', calc.add(5));
console.log('calc.subtract(3):', calc.subtract(3));
console.log('calc.multiply(2):', calc.multiply(2));

const dog = new Dog('Rex', 3, 'German Shepherd');
console.log('dog.info:', dog.info);
dog.bark();

processData().then(() => {
  console.log('Processed numbers sum:', processed);
  console.log('Status:', status, 'Message:', message);
  console.log('Counter:', counter.increment(), counter.increment());
  console.log('Dynamic obj:', obj.method());
});

const debouncedLog = utils.debounce((msg) => console.log('Debounced:', msg), 500);
debouncedLog('Hello');
debouncedLog('World');

if (typeof window !== 'undefined') {
  window.__demo = {
    calc,
    dog,
    processed,
    status,
    counter,
  };
}

压缩效果:

代码体积减小:39.72%

代码综合性能提升约:7.6%,解析速度提升约:13.5%,运行速度提升约:5.0%

erlang 复制代码
压缩前体积:5.37 KB
压缩后体积:3.24 KB
代码体积减小:39.72%

代码共压缩22处,明细:

简化if语句或三元运算 12 个
常量替换为直接引用 2 个
局部变量名缩短 8 个

代码综合性能提升约:7.6%,解析速度提升约:13.5%,运行速度提升约:5.0%

压缩后的代码:

javascript 复制代码
const config={name:'CompressionDemo',version:'1.0.0',debug:true,features:['minify','mangle','deadCode']};const{name,version,features}=config;function createCalculator(initialValue=0){let _v=initialValue;return{add:(step=1)=>{_v+=step;return _v;},subtract:(step=1)=>{_v-=step;return _v;},multiply:factor=>{_v*=factor;return _v;},getValue:()=>_v,reset:()=>{_v=initialValue;return _v;}};}class Animal{constructor(name,age){this.name=name;this.age=age;this._secret='classified';}get info(){return`${this.name} (${this.age} years old)`;}set secret(value){if(typeof value==='string'&&value.length>0){this._secret=value;}}static compareAge(a,b){return a.age-b.age;}}class Dog extends Animal{constructor(name,age,breed){super(name,age);this.breed=breed;}bark(){console.log(`Woof! I'm ${this.name}`);}get info(){return`${super.info}, breed: ${this.breed}`;}}function fetchData(flag){return new Promise((resolve,reject)=>{setTimeout(()=>{if(flag){resolve({data:'sample data',status:'success'});}else{reject(new Error('Invalid flag'));}},100);});}async function processData(){try{const _r=await fetchData(true);console.log('Fetched:',_r);return _r;}catch(error){console.error('Error:',error.message);return null;}}const numbers=[5,12,8,130,44,2,99,3];const processed=numbers.filter(n=>n%2===0).map(n=>n*2).sort((a,b)=>a-b).reduce((acc,n)=>acc+n,0);function getStatus(score){if(score>=90)return'A';if(score>=80)return'B';if(score>=70)return'C';if(score>=60)return'D';return'F';}const status=getStatus(85);const message=status==='A'?'Excellent!':status==='B'?'Good job!':status==='C'?'Keep trying':'Needs improvement';function sumArray(arr){let _s=0;for(let i=0;i<arr.length;i++){_s+=arr[i];}return _s;}function printItems(items){for(const _i2 of items){console.log(_i2);}}function doubleValues(arr){const _r2=[];arr.forEach((val,idx)=>{_r2.push(val*2+idx);});return _r2;}const counter=function(){let _c=0;return{increment:()=>++_c,decrement:()=>--_c,getCount:()=>_c};}();const key='dynamicKey';const obj={key,[key]:'dynamicValue',method(){return this.key;}};const utils={debounce(fn,delay=300){let _t=null;return function(...args){clearTimeout(_t);_t=setTimeout(()=>fn.apply(this,args),delay);};},throttle(fn,limit=200){let _i3=false;return function(...args){if(!_i3){fn.apply(this,args);_i3=true;setTimeout(()=>_i3=false,limit);}};}};const UNUSED_CONST='This is never used';function unusedFunction(){return'I am dead code';}var unusedVar=42;if(typeof module!=='undefined'&&module.exports){module.exports={createCalculator,Animal,Dog,processData,processed,status,message,counter,utils};}console.log('=== Compression Demo Output ===');const calc=createCalculator(10);console.log('calc.add(5):',calc.add(5));console.log('calc.subtract(3):',calc.subtract(3));console.log('calc.multiply(2):',calc.multiply(2));const dog=new Dog('Rex',3,'German Shepherd');console.log('dog.info:',dog.info);dog.bark();processData().then(()=>{console.log('Processed numbers sum:',processed);console.log('Status:',status,'Message:',message);console.log('Counter:',counter.increment(),counter.increment());console.log('Dynamic obj:',obj.method());});const debouncedLog=utils.debounce(msg=>console.log('Debounced:',msg),500);debouncedLog('Hello');debouncedLog('World');if(typeof window!=='undefined'){window.__demo={calc,dog,processed,status,counter};}

最后,再实测一下执行效率:

注:使用上面第三次示例压缩前后的JS代码;测试环境:NodeJS。

第一次测试:

压缩前的代码:

压缩后的代码:

第二次测试:

压缩前的代码:

压缩后的代码:

第三次测试:

压缩前的代码:

压缩后的代码:

第四次测试(在浏览器中):

由测试可知,JS压缩可减小代码体积、提升执行效率,真实有效!

相关推荐
snow@li1 小时前
Vue Axios封装与SpringBoot Payload封装全景关联分析(前后端数据交互底层闭环)
前端·vue.js·spring boot
进击的丸子1 小时前
虹软人脸SDK 调用常见问题和最佳实践指南
后端
用户298698530141 小时前
Word 转 PDF 的 3 种自动化实现:从桌面操作到后端服务集成
java·人工智能·后端
Csvn1 小时前
🐛 React StrictMode 下 useEffect 执行两次:不是 Bug,是特性
前端
newerp1 小时前
桥接模式 (Bridge Pattern)
后端
Gopher_HBo1 小时前
Go语言设计模式(四)生成器模式
后端
做好一个小前端1 小时前
ECharts 折线图大数据量性能优化参考
前端·性能优化·echarts
长栎1 小时前
你的订单状态机写成 switch-case 了?State 模式跟策略模式差了一个维度
后端