search
HomeJavajavaTutorialHow to improve the efficiency of using Java reflection

How to improve the efficiency of using Java reflection

Apr 28, 2019 pm 04:33 PM
java reflectionefficiency

In our daily work or interviews, we often encounter the knowledge point of "reflection". Through "reflection" we can dynamically obtain object information and flexibly call object methods, etc., but at the same time we use it Along with the emergence of another sound, that is, "reflection" is very slow and should be used sparingly. Is reflection really slow? How much slower is it than when we usually create objects and call methods? I guess many people have never tested it, they just "heard" it. Let's directly experience "reflection" directly through some test cases.

Text

Prepare the test object

The following defines a test class TestUser, which only has the id and name attributes, as well as their getter/setter methods, and a self- Define the sayHi method.

public class TestUser {    private Integer id;    private String name;    
    public String sayHi(){        return "hi";
    }    public Integer getId() {        return id;
    }    public void setId(Integer id) {        this.id = id;
    }    public String getName() {        return name;
    }    public void setName(String name) {        this.name = name;
    }
}

Test to create 1 million objects

// 通过普通方式创建TestUser对象@Testpublic void testCommon(){    long start = System.currentTimeMillis();
    TestUser user = null;    int i = 0;    while(i<1000000){
        ++i;
        user = new TestUser();
    }    long end = System.currentTimeMillis();
    System.out.println("普通对象创建耗时:"+(end - start ) + "ms");
}//普通对象创建耗时:10ms
// 通过反射方式创建TestUser对象@Testpublic void testReflexNoCache() throws Exception {    long start = System.currentTimeMillis();
    TestUser user = null;    int i = 0;    while(i<1000000){
        ++i;
        user = (TestUser) Class.forName("ReflexDemo.TestUser").newInstance();
    }    long end = System.currentTimeMillis();
    System.out.println("无缓存反射创建对象耗时:"+(end - start ) + "ms");
}//无缓存反射创建对象耗时:926ms

In the above two test methods, the author tested each 5 times, took an average of the time they consumed, and output You can see from the results that one is 10ms and the other is 926ms. When 1 million objects are created, reflection is actually about 90 times slower. wtf? Is the gap so big? Is reflection really that slow? Next, the author changes the reflection posture and continues to test it to see what the result is?

// 通过缓存反射方式创建TestUser对象@Testpublic void testReflexWithCache() throws Exception {    long start = System.currentTimeMillis();
    TestUser user = null;
    Class rUserClass = Class.forName("RefleDemo.TestUser");    int i = 0;    while(i<1000000){
        ++i;
        user = (TestUser) rUserClass.newInstance();
    }    long end = System.currentTimeMillis();
    System.out.println("通过缓存反射创建对象耗时:"+(end - start ) + "ms");
}//通过缓存反射创建对象耗时:41ms

In fact, we can find through the code that the Class.forName method is more time-consuming. It actually calls a local method, through which the JVM is asked to find and load the specified class. Therefore, when we use it in the project, we can cache the Class object returned by Class.forName, and obtain it directly from the cache the next time it is used, which greatly improves the efficiency of obtaining Class. In the same way, when we obtain Constructor, Method and other objects, we can also cache them for use to avoid time-consuming creation every time they are used.

Testing the reflection calling method

@Testpublic void testReflexMethod() throws Exception {    long start = System.currentTimeMillis();
    Class testUserClass = Class.forName("RefleDemo.TestUser");
    TestUser testUser = (TestUser) testUserClass.newInstance();
    Method method = testUserClass.getMethod("sayHi");    int i = 0;    while(i<100000000){
        ++i;
        method.invoke(testUser);
    }    long end = System.currentTimeMillis();
    System.out.println("反射调用方法耗时:"+(end - start ) + "ms");
}//反射调用方法耗时:330ms
@Testpublic void testReflexMethod() throws Exception {    long start = System.currentTimeMillis();
    Class testUserClass = Class.forName("RefleDemo.TestUser");
    TestUser testUser = (TestUser) testUserClass.newInstance();
    Method method = testUserClass.getMethod("sayHi");    int i = 0;    while(i<100000000){
        ++i;
        method.setAccessible(true);
        method.invoke(testUser);
    }    long end = System.currentTimeMillis();
    System.out.println("setAccessible=true 反射调用方法耗时:"+(end - start ) + "ms");
}//setAccessible=true 反射调用方法耗时:188ms

Here we reflect and call the sayHi method 100 million times. After calling method.setAccessible(true), found that it is nearly half faster. Looking at the API, we can learn that jdk will perform security access checks when setting the acquisition field and calling methods, and such operations will be time-consuming, so you can turn off security checks through setAccessible(true), thereby improving reflection efficiency.

The Ultimate Reflection

In addition to the above methods, is there any way to use reflection to the extreme? Here we introduce ReflectASM, a high-performance reflection toolkit. It is a reflection mechanism implemented through bytecode generation. The following is a performance comparison with Java reflection.

How to improve the efficiency of using Java reflection

Conclusion

Finally, to summarize, In order to better use reflection, we should load the relevant configuration and data required for reflection into the memory when the project starts, and then run Each stage fetches these metadata from the cache for reflection operations. You don’t have to be afraid of reflection. The virtual machine is constantly being optimized. As long as we use the right method, it is not as slow as “rumored”. When we have the ultimate pursuit of performance, we can consider using third-party packages to directly Code operation.

Related tutorials: Java video tutorial

The above is the detailed content of How to improve the efficiency of using Java reflection. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:OSCHINA. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)