How to improve the efficiency of using Java reflection
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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



DeepMind’s AI agent is at work again! Pay attention, this guy named BBF mastered 26 Atari games in just 2 hours. His efficiency is equivalent to that of humans, surpassing all his predecessors. You know, AI agents have always been effective in solving problems through reinforcement learning, but the biggest problem is that this method is very inefficient and requires a long time to explore. Picture The breakthrough brought by BBF is in terms of efficiency. No wonder its full name can be called Bigger, Better, or Faster. Moreover, it can complete training on only a single card, and the computing power requirements are also much reduced. BBF was jointly proposed by Google DeepMind and the University of Montreal, and the data and code are currently open source. The highest attainable human

PyCharm is a powerful Python integrated development environment (IDE) that is widely used by Python developers for code writing, debugging and project management. In the actual development process, most developers will face different problems, such as how to improve development efficiency, how to collaborate with team members on development, etc. This article will introduce a practical guide to remote development of PyCharm to help developers better use PyCharm for remote development and improve work efficiency. 1. Preparation work in PyCh

StableDiffusion is an open source deep learning model. Its main function is to generate high-quality images through text descriptions, and supports functions such as graph generation, model merging, and model training. The operating interface of the model can be seen in the figure below. How to generate a picture. The following is an introduction to the process of creating a picture of a deer drinking water. When generating a picture, it is divided into prompt words and negative prompt words. When entering the prompt words, you must describe it clearly and try to describe the scene, object, style and color you want in detail. . For example, instead of just saying "the deer drinks water", it says "a creek, next to dense trees, and there are deer drinking water next to the creek". The negative prompt words are in the opposite direction. For example: no buildings, no people , no bridges, no fences, and too vague description may lead to inaccurate results.

Java reflection is a powerful tool that allows you to access the private fields and methods of a class, thereby revealing the inner workings of the software. This is useful in areas such as reverse engineering, software analysis and debugging. To use Java reflection, you first need to import the java.lang.reflect package. Then, you can use the Class.forName() method to obtain the Class object of a class. Once you have a Class object, you can use various methods to access the fields and methods of the class. For example, you can use the getDeclaredFields() method to get all fields of a class, including private fields. You can also use the getDeclaredMethods() method

With the rapid development of the Internet, the importance of databases has become increasingly prominent. As a Java developer, we often involve database operations. The efficiency of database transaction processing is directly related to the performance and stability of the entire system. This article will introduce some techniques commonly used in Java development to optimize database transaction processing efficiency to help developers improve system performance and response speed. Batch insert/update operations Normally, the efficiency of inserting or updating a single record into the database at one time is much lower than that of batch operations. Therefore, when performing batch insert/update

Title: Python makes life more convenient: Master this language to improve work efficiency and quality of life. As a powerful and easy-to-learn programming language, Python is becoming more and more popular in today's digital era. Not just for writing programs and performing data analysis, Python can also play a huge role in our daily lives. Mastering this language can not only improve work efficiency, but also improve the quality of life. This article will use specific code examples to demonstrate the wide application of Python in life and help readers

To master the role of sessionStorage and improve front-end development efficiency, specific code examples are required. With the rapid development of the Internet, the field of front-end development is also changing with each passing day. When doing front-end development, we often need to process large amounts of data and store it in the browser for subsequent use. SessionStorage is a very important front-end development tool that can provide us with temporary local storage solutions and improve development efficiency. This article will introduce the role of sessionStorage,

The role of subnet mask and its impact on network communication efficiency Introduction: With the popularity of the Internet, network communication has become an indispensable part of modern society. At the same time, the efficiency of network communication has also become one of the focuses of people's attention. In the process of building and managing a network, subnet mask is an important and basic configuration option, which plays a key role in network communication. This article will introduce the role of subnet mask and its impact on network communication efficiency. 1. Definition and function of subnet mask Subnet mask (subnetmask)
