java - 反射性能 : quality byte code in JVM

标签 java reflection coding-style bytecode

编辑 2: 具有完全面向对象 实现的程序是否具有高性能?大多数 framework 都是用它的全部功能编写的。但是,反射 也被大量用于实现它,例如AOP依赖注入(inject)反射的使用在一定程度上影响了性能。

那么,使用反射是一种好的做法吗?除了编程语言构造的反射之外,还有其他选择吗?应在多大程度上使用反射

最佳答案

反射,就其本身和本质而言,是缓慢的。参见 this question更多细节。 这是由几个原因造成的。 Jon Skeet explains it nicely:

Check that there's a parameterless constructor Check the accessibility of the parameterless constructor Check that the caller has access to use reflection at all Work out (at execution time) how much space needs to be allocated Call into the constructor code (because it won't know beforehand that the constructor is empty)

基本上,反射必须在调用之前执行上述所有步骤,而普通方法调用所要做的要少得多。

The JITted code for instantiating B is incredibly lightweight. Basically it needs to allocate enough memory (which is just incrementing a pointer unless a GC is required) and that's about it - there's no constructor code to call really; I don't know whether the JIT skips it or not but either way there's not a lot to do.

话虽如此,在很多情况下,Java 的动态性不足以满足您的需求,而反射提供了一种简单干净的替代方案。考虑以下场景:

  1. 您有大量代表各种项目的类,即 CarBoatHouse
  2. 它们都扩展/实现了同一个类:LifeItem
  3. 您的用户输入 3 个字符串之一,“Car”、“Boat”或“House”。
  4. 您的目标是根据参数访问 LifeItem 的方法。
  5. 想到的第一个方法是构建一个 if/else 结构,并构建所需的 LifeItem。但是,这不是很可扩展,一旦您拥有数十个 LifeItem 实现,就会变得非常困惑。

反射在这里可以提供帮助:它可用于根据名称动态构造 LifeItem 对象,因此“Car”输入将被分派(dispatch)给 Car 构造函数。突然间,原本可能是数百行的 if/else 代码变成了一行简单的反射。由于引入了带字符串的 switch 语句,后一种情况在 Java 7+ 平台上不会那么有效,但即便如此,我还是希望避免出现具有数百个 case 的 switch。以下是大多数情况下清洁度之间的区别:

没有反射(reflection):

public static void main(String[] args) {
   String input = args[0];
   if(input.equals("Car"))
      doSomething(new Car(args[1]));
   else if(input.equals("Boat"))
      doSomething(new Boat(args[1]));
   else if (input.equals("House"))
      doSomething(new House(args[1]));
   ... // Possibly dozens more if/else statements
}

而通过使用反射,它可以变成:

public static void main(String[] args) {    
   String input = args[0];
   try {
      doSomething((LifeItem)Class.forName(input).getConstructor(String.class).newInstance(args[1]));
   } catch (Exception ie) {
      System.err.println("Invalid input: " + input);
   }  
}

就我个人而言,我会说后者比第一个更简洁、更简洁且更易于维护。最后,这是个人偏好,但这只是反射有用的众多情况之一。

此外,在使用反射时,您应该尝试缓存尽可能多的信息。换句话说,使用简单、合乎逻辑的东西,比如如果可以的话,不要到处调用 get(Declared)Method:相反,将它存储在一个变量中,这样你就没有重新获取引用的开销随时随地使用它。

因此,这是反射(reflection)的赞成和反对的两个极端。总而言之,如果反射提高了代码的可读性(就像在呈现的场景中那样),一定要去做。如果这样做,只需考虑减少 get* 反射调用的数量:这些是最容易修剪的。

关于java - 反射性能 : quality byte code in JVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14703959/

相关文章:

java - 如何关闭Android中的所有 Activity ?

java - 正则表达式 : who's greedier?

java - 拦截方法调用

用于编码标准的 JavaScript 工具

java - 单击 JPopupMenu 时 JPopupPanel 关闭

java - 如何设置元素在所有设备上保持原位

scala - 如何让 Scala ToolBox 查看 REPL 定义?

go - 使用 reflect 模拟 struct.field

coding-style - 使用制表符而不是空格时保持最大行长度?

html - CSS LIst 样式 Font Awesome 不工作