zoukankan      html  css  js  c++  java
  • Knowledge Point 20180308 Dead Code

    不知道有没有前辈注意过,当你编写一段“废话式的代码时”会给出一个Dead Code警告,点击警告,那么你所写的废物代码会被编译器消除,那么如果你不理睬这个警告呢?编译后会是什么样的呢?下面我们写点代码,来查看一下编译后的结果,这里使用反编译工具jd-gui.exe。代码如下:

    package cn.five.four;
    
    public class Test {
        public static void main(String[] args) {
            int a = 7;
            int b = 9;
            test1();
            test2(a, b);
        }
        //废话代码--条件语句中,已经可以确定条件真假的会被认为是死代码(Dead Code),也叫无效代码
        public static void test1(){
            if(5>6){
                System.out.println("jdk1.7输出废话代码!!");
            }else {
                System.out.println("都不用编译,你自己都知道要输出这段代码!");
            }
        }
        //条件不确定的不是死代码
        public static void test2(int a,int b){
            if(a>b){
                System.out.println("条件语句块中只有一句代码!");
            }else if (a == b) {
                System.out.println("条件语句块中只有两句代码!");
                System.out.println("条件语句块中只有两句代码!");
            }else {
                System.out.println("会输出这句吗?");
            }
        }
    }

    反编译

    package cn.five.four;
    
    import java.io.PrintStream;
    
    public class Test
    {
      public static void main(String[] args)
      {
        int a = 7;
        int b = 9;
        test1();
        test2(a, b);
      }
      
      public static void test1()
      {
        System.out.println("都不用编译,你自己都知道要输出这段代码!");
      }
      
      public static void test2(int a, int b)
      {
        if (a > b)
        {
          System.out.println("条件语句块中只有一句代码!");
        }
        else if (a == b)
        {
          System.out.println("条件语句块中只有两句代码!");
          System.out.println("条件语句块中只有两句代码!");
        }
        else
        {
          System.out.println("会输出这句吗?");
        }
      }
    }

     上面我们知道了编译器在编译后会自动将死代码优化为已知的结果,这是编译器的优化。不过聪明如我们的程序员应该不至于写出这样的代码,在这里仅仅是表明编译器也是可以优化我们的代码的。

  • 相关阅读:
    监控网速
    nginx与apache 对比 apache是同步多进程模型,一个连接对应一个进程;nginx是异步的,多个连接(万级别)可以对应一个进程
    shell 爬虫
    shell 读写远程数据库
    tmp
    交换分区 在dd命令执行期间 top 其消耗系统约14%的cpu,而mem占比约为0
    中间变量 加层 对解决问题的思路 逆序生成
    ALLOWED_HOSTS = ['*']
    搭建一个简单的Python的Web环境 监控服务器内存 线程 进程 网络
    小米加步枪
  • 原文地址:https://www.cnblogs.com/lin-jing/p/8025279.html
Copyright © 2011-2022 走看看