代码之家  ›  专栏  ›  技术社区  ›  Aloha

Java-内联代码有好处吗?

  •  12
  • Aloha  · 技术社区  · 10 年前

    我做了一些研究,但我大多看到了c++的答案。我最接近的是 this 。我也看到了 this page 但这并不能解释什么。

    如果我使用第二段代码,有什么好处吗?会有明显的性能差异吗?记忆呢?如果重复做会怎么样?

    现在我有了这个功能。我确信这样做的好处是代码可读性:

    private static Bitmap resize(Bitmap image, int maxWidth) {
        float widthReducePercentage = ((float) maxWidth / image.getWidth());
        int scaledHeight = Math.round(image.getHeight() * widthReducePercentage);
    
        return Bitmap.createScaledBitmap(image, maxWidth, scaledHeight, true);
    }
    

    现在,我有第二段代码:

    private static Bitmap resize(Bitmap image, int maxWidth) {
        return Bitmap.createScaledBitmap(image, maxWidth, Math.round(image.getHeight() * (float) maxWidth / image.getWidth()), true);
    }
    

    一个更简单的例子是:

    for(;;) {
        String foo = "hello";
        Console.print(foo + "world");
    }
    

    for(;;) {
        Console.print("hello" + "world");
    }
    
    4 回复  |  直到 9 年前
        1
  •  10
  •   Community Mohan Dere    9 年前

    第一:这不是“内联”的意思。请参见: What is inlining?

    第二:不,绩效不会有任何可衡量的差异。在这两个代码示例中,两个版本的编译代码很可能相同。

        2
  •  5
  •   LIProf    10 年前

    我定义了两个简单的类 Test1 Test2 并编译它们。

    public class Test1{
        public String f(){
            String s = "Hello";
            String t = "There";
            return s + t;
        }
    }
    

    public class Test2{
        public String f(){
            return "Hello" + "There";
        }   
    }
    

    令我惊讶的是,.class文件的大小不同。

    -rw-r--r--  1 csckzp  staff  426 Dec 23 19:43 Test1.class
    -rw-r--r--  1 csckzp  staff  268 Dec 23 19:43 Test2.class
    

    也许我不应该感到惊讶,因为一些符号信息与代码一起存储。我通过在线反编译器运行了.class文件。 测试1 基本上是按照键入的方式重建的。 测试2 另一方面,以这种方式反编译:

    public class Test2 {
        public String f() {
            return "HelloThere";
        }
    }
    

    编译器的优化清楚地显示在这里。也许在Java中对于非紧凑代码有一个小的惩罚。

        3
  •  3
  •   Kyle Emmanuel    10 年前

    他们都一样。前者比后者更清楚。

    在某些情况下,如下面的块,单行程序很有用。

    public boolean isEmpty() {
       return getCount() != 0;
    }
    

    如果你想让它更容易阅读,尤其是当涉及到方程时 variable .一行程序使其简单而简短,但适合于简短的逻辑。

    这是我个人的看法。

        4
  •  2
  •   meriton    10 年前

    虽然局部变量能够在字节码的转换中生存,但它们不太可能在实时编译中生存。此外,即使存在局部变量,它们也不会显著影响该方法的性能,因为重新缩放位图比存储或检索局部变量要贵几个数量级。

    关于字符串连接的第二个示例强调了此规则的一个小例外,因为局部变量的存在可能会抑制对常量字符串连接的编译时求值。然而,这不太可能对程序的运行时间产生重大影响,因为您可能不会经常连接常量字符串。

    一般来说,内联局部变量对运行时性能的影响很难测量,更不用说显著了。因此,通过使代码易于阅读和推理,您的时间可以更好地优化程序员的性能。