• 生产环境日志打印console.log内存溢出解决方法


    在开发环境里面,开发者经常喜欢使用 console.log 进行日志打印,很好的提高了开发者的开发效率,但是这样容易产生新的问题,因为console的使用,影响内存的滥用,可能造成内存溢出

    分析内存上述的原因

    传递给 console.log 的对象,影响了它的垃圾回收,导致内存居高不下。

    验证实例

    Memory.html
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Memory</title>
      </head>
      <body>
        <input type="button" value="click" class="button" />
        <br>
        <br>
        <label><input type="checkbox" class="checkbox" value="" />关闭日志打印<label>
        <script>  
          class Memory {
            constructor(){
                this.init();
            }
            data = null;
            init(){
              this.data = new Array(100000).join('*');
              console.log("Leaking an object: ", new Date(), this);
              console.warn("Leaking an object: ", new Date(), this);
              console.error("Leaking an object: ", new Date(), this);
            }
            destroy(){
                this.data = null;
            }
          }
          document.getElementsByClassName("button")[0].addEventListener('click', ()=>{
            new Memory();
          });
          document.getElementsByClassName("checkbox")[0].addEventListener('click', (val)=>{
            if(val.target.checked){
                console.log = ()=>{}
                console.warn = ()=>{}
                console.error = ()=>{}
            }else{
                location.reload();
            }
          });
        </script>   
      </body>
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    这里使用Chrome谷歌浏览器的开发者工具中的Performance来进行演示:
    (实验两次,第一次实验默认不关闭日志打印,第二次实验关闭日志打印)

    1. 开始记录内存变化Performance
    2. 连续点击三次click,每次间隔一下click
    3. 结束记录结束记录

    验证结果图

    不关闭日志打印
    三次创建对象,console打印日志,内存持续走高,无垃圾回收

    日志

    关闭日志打印
    三次创建对象,无console打印日志,在第二次创建对象完毕的时候,内存下降,因此判断这个地方执行了垃圾回收

    日志

    生产环境关闭日志打印核心代码

    原理是用空方法覆盖console里面原来的方法

    这里只覆盖了console对象里面的 log、warn、error 这三个常用的方法,一般开发打印日志的时候,只会使用这些方法

    console.log = ()=>{}
    console.warn = ()=>{}
    console.error = ()=>{}
    
    • 1
    • 2
    • 3
  • 相关阅读:
    golang设计模式——命令模式
    2407. 最长递增子序列 II-动态规划暴力解法和线段树
    20220701
    2D物理系统——物理材质 & 恒定力
    c语言入门---调试技巧
    结束八天了,还是无法与她和解. --vulnhub 靶场
    【Linux问题】This account is currently not available.
    透视星环科技上市:基础工具、技术融合、场景应用三维击穿
    AppleID切换验证手机
    蜂鸣器(51单片机)
  • 原文地址:https://blog.csdn.net/qq_26069551/article/details/127891102