Why Is Reflection So Much Slower Than new? Java Object Creation Benchmarks
This article explains the fundamental differences between using the new operator and Java reflection to instantiate objects, presents a performance benchmark showing reflection’s significant overhead, analyzes the underlying reasons, and outlines practical scenarios where each approach is appropriate.
1. Basic Concepts
In Java, objects are usually created with the new operator, but they can also be instantiated via reflection.
The article asks when to use each method and compares their performance.
// new way
ReflectDemo reflectDemo = new ReflectDemo();
// reflection ways
Class<ReflectDemo> reflectDemoClass = ReflectDemo.class;
Class<?> aClass = Class.forName("com.whale.springtransaction.transactiondemo.reflectdemo.ReflectDemo");
Class<? extends Class> aClass = reflectDemoClass.getClass();2. Performance Comparison
public class ReflectDemo {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
proxyObject();
newObject();
}
// new object
public static void newObject() {
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
ReflectDemo reflectDemo = new ReflectDemo();
}
long endTime = System.currentTimeMillis();
System.out.println("new耗时为:" + (endTime - startTime));
}
// reflection object
public static void proxyObject() throws IllegalAccessException, InstantiationException {
long startTime = System.currentTimeMillis();
Class<ReflectDemo> reflectDemoClass = ReflectDemo.class;
for (int i = 0; i < 100000000; i++) {
ReflectDemo reflectDemo = reflectDemoClass.newInstance();
}
long endTime = System.currentTimeMillis();
System.out.println("反射耗时为:" + (endTime - startTime));
}
}The test shows that creating 100 000 000 objects with new is many times faster than using reflection.
Reasons include:
Method#invoke performs argument boxing/unboxing.
Reflection requires accessibility checks.
Reflective calls cannot be inlined.
JIT cannot optimize reflective calls.
3. When to Use Reflection vs new
Reflection use cases:
1. Spring uses reflection to instantiate beans and put them into the IoC container.
2. Loading JDBC drivers with Class.forName().
3. Reverse engineering, e.g., decompilation.
4. Using reflection to store a String in an ArrayList<int>. // Differences between new and reflection
1. Objects created with new cannot access private members; reflection can bypass access checks with setAccessible().
2. new requires the class name at compile time; reflection can instantiate without knowing the type at compile time.Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
