gpt4 book ai didi

java - 优化:全局字符串与调用枚举类

转载 作者:行者123 更新时间:2023-12-01 22:12:43 25 4
gpt4 key购买 nike

我有这个枚举类,

public enum Test {
A("A"),
B("B"),
C("C"),
D("D");

private final String test;

Test(final String test) {
this.test = test;
}

public String getTestCode() {
return stateCode;
}
}

在单元测试类中,我声明了以下全局变量,

private static final String A = "A";

问题:

在单元测试类中,将对A的值进行多次测试。

为了效率,纯粹从优化的角度来看(无论优化多小),哪个会更有效率

  • 调用全局声明的变量,
  • 通过以下方式调用枚举类

    Test.A.getTestCode();

或者根本没有任何区别?

最佳答案

private static final String A = "A"; 是编译时常量,其值将被内联,因此代码如下

String x = YourClass.A;

将被编译为

String x = "A";

如果出现

String x = Test.A.getTestCode();

在接收“A”之前,您需要调用getTestCode()

<小时/>

您可以使用javap -c命令检查它,这将允许我们查看类的编译版本。所以对于这样的代码

public class Demo {

private static final String A = "A";

void test1(){
String x = Demo.A;
}

void test2(){
String x = "A";
}

void test3(){
String x = Test.A.getTestCode();
}

}

javap -c 演示 显示

  public com.stackoverflow.Demo();
Code:
0: aload_0
1: invokespecial #12 // Method java/lang/Object."<init>":()V
4: return

void test1();
Code:
0: ldc #8 // String A
2: astore_1
3: return

void test2();
Code:
0: ldc #8 // String A
2: astore_1
3: return

void test3();
Code:
0: getstatic #22 // Field Test.A:LTest;
3: invokevirtual #27 // Method Test.getTestCode:()Ljava/lang/String;
6: astore_1
7: return

这意味着方法test1test2实际上是相同的,而test3首先需要访问A枚举,然后调用其 getTestCode 方法。

关于java - 优化:全局字符串与调用枚举类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31576236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com