[Memory Leak] 1. console.log cause memory leak

Zhentiw發表於2024-11-04

Example code:

<template>
  <button @click="handleClick">Hello, Vue-CLI</button>
</template>

<script>
export default {
  methods: {
    handleClick() {
      const arr = new Array(100000).fill(0);
      console.log(arr);
      return arr
    },
  },
};
</script>

This code will cause memory leak, the reason is due to when you use console.log(arr), GC cannot destory arranymore, otherwise, in console, you cannot see the arranymore.

In chrome, the memory leak problem only happens when you open the devTool, so it depends on Browsers.

We can remove consoleby using CLI tool, for example,

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
  },
})

相關文章