Does JAVA reflection reduce the performance of your program?

Source: Internet
Author: User
Tags reflection

Two days ago, I wrote the article "starting from the reconstruction of three thousand lines of code into 15 lines of code". I saw some comments still questioning the reflection performance, it seems that the program uses reflection, just like a tractor. I think there is nothing to discuss about this topic. There are already too many articles on the Internet to address this issue. If you have any questions, you can refer to relevant articles on the Internet. However, when I first came up with programming, I also encountered this kind of confusion and found it on the internet. I have explained it from various perspectives, and I have basically mentioned the essence, but there are still many people who don't understand it. I will talk about it from my perspective here.

Reflection must be slower than direct calls

Without a doubt, this article does not prove how efficient reflection is.

The express delivery is very popular now. Let's give an example of express delivery. If the courier is in your residential area, then you report an address: xx building xx, then the courier can immediately know where you are and go directly to your home. However, if the courier is here for the first time, do he have to first check baidu map to see how to drive the car, and then, when he arrives at the community, do he have to ask how to find building xx of thing management? Then, it is possible that two circles are transferred downstairs to your door.

Let's look at the above scenario. If the courier is not familiar with your community, will it be slower? His time is mainly spent searching Baidu Map and asking about property management. OK, the same is true for reflection. Because I don't know anything in advance, I have to spend some time querying other materials before I can find you. If you are interested, you can view the implementation principles of reflection and the concepts related to MetaData.

How slow is reflection than direct call?

Well, we know that reflection must be slow. Is reflection useless? When some people hear it slowly, they are very anxious to draw conclusions, reflecting how it works and how it cannot be used. However, reflection is much slower than direct calling. Can you give me actual data? In fact, many people only have a vague concept of performance without numerical support. Previously, I found a class library for dynamic parsing expressions for my colleagues. He thought it was not very useful. He was very clever and quickly found a class library that could use DataTale. Compute to implement dynamic parsing of formulas. I asked him, what is the performance difference between this method and the class library I gave? He told me that the execution was very fast and could not be completed within 1 second. As soon as I heard it, I thought something was wrong. Your thoughts are still in seconds. What performance do you want to talk to me about?

How can we determine the performance of a function? Because function execution is too fast and fast, you need a slow-down mirror to capture its speed. How? You can execute a function 1 million times or 10 million times to understand the performance of a function. That is to say, if you want to judge the performance, you cannot stay in seconds or milliseconds. You must replace it with another concept to know the real performance. As a result, my colleague performed these two methods times. Indeed, the class library I provided was 8 seconds faster than his class library.

Now let's take the Factory method I provided two days ago for testing. For the implementation of CodeTimer, refer to Zhao's article "a simple performance counter: CodeTimer":

The test method is as follows:

The code is as follows: Copy code

[Test]
Public void TestReflector ()
{
CodeTimer. Time ("Direct", 100*10000,
() =>
        {
Var instance = new ConnectionTest ();
});

CodeTimer. Time ("Reflect", 100*10000,
() =>
        {
This. GetType (). Assembly. CreateInstance ("TestPropertyGrid. ConnectionTest ");
});
}



The test results are as follows:

Direct
Time Elapsed: 25 ms
CPU Cycles: 57,582,163
Gen 0: 14
Gen 1: 0

Reflect
Time Elapsed: 3,231 ms
CPU Cycles: 8,001,720,795
Gen 0: 269
Gen 1: 1

No, our magnifiers have taken effect. Now we can come to the conclusion that during the execution of 1 million times, reflection may slow down direct calls by 50 to Times ~ 100 times. 100 times. At first glance, there is a big difference. However, as I mentioned above, don't draw conclusions. You have to look at the prerequisites. Since ancient times, we have always liked to stand out from the rules. For example, the idiom "report with morality and resentment" seems like the ancients have said that we may encounter bad things, but you cannot hate it. To treat others better, others will slap you on the left, you should stretch your right face and ask him to try again. But what is this idiom?

Or: "What is it like to report complaints by virtue of morality ?"
Zi Yue: "Why do we report the virtues? "

Old Kong actually means that if someone else is nice to you, then you will be nice to him. If he asks you to provoke you, you will do his work! You see, dumb?
How many situations do we need to consider the impact of reflection?

I think this situation is very rare, and we don't need to consider this in most cases. As mentioned in my previous article, how many entities are there in your program? Are there 1 million? If you only create a new one in the pop-up window, is the impact of 10 s per million important to you?

In addition, some people say that if I have such a requirement, it would be too slow to put an object new for 1 million times? Is there any such situation? Yes! For example, if I have million records, I need to retrieve them and assign them to a Model class through reflection.

However, if you really think so, I can only say that you have been sitting in the office for a long time and your head is rusty. You should climb a mountain and soak up a girl. If you need to reflect an object 1 million times, you should cache the object. Taking the example above for example, if the courier sent 1 million times of express delivery to people in the community, he still had to go to Baidu map every time and then asked the property management staff, you have not taken him off yet, so your head is not funny, or you are a willful rich man.

What is the difference between the above code and direct call if it is executed 1 million times after being cached? I will not post the code here, so that you may not be interested in the result directly. I will try the code again, so I am more impressed.

There is no faster way. For example, if your courier is using iPhone 4, you can buy him 6 +. In. net, Emit-related methods are provided for faster reflection. Here we will give you a wheel "Dapper" that quickly assigns a value to the Model through reflection and create it on your own.
Should reflection be used in programming?

In fact, after reading the above text, I believe you all have a preliminary judgment, and my opinion is: in most cases, you can use reflection.

If you think your program is slow due to reflection, please first take a look at it with a slowing down mirror to see if it is a reflection problem. If you are sure it is a reflection problem, consider whether you are not using reflection or not, just like the courier who has gone through the road for 1 million times. Finally, if you think the performance is not enough, I suggest you upgrade the hardware, the hardware performance has increased by 3%, which is better than that. If you ask a great engineer to help you with this extreme optimization, I think it is right that "engineers are much more expensive than servers ". If you still have to compete with me, then there is no way. Your program's performance requirements have exceeded the scope discussed in this article. If you have such requirements, I don't think you need to read this article, because you have enough knowledge about the system language.

Most of the time, we will attribute the performance of the program to the programming language, or use reflection and other technologies, and seldom care about your own code. This mentality will lead to slower and slower development of your technology, because you have lost your desire for knowledge and a desire to pursue technological progress. Remember, more often, what affects the performance of our programs is your programming philosophy and your attitude towards coding!
Summary

Well, after talking so much, it is estimated that many people simply drag it to the end of the article and then silently likes a like because of the many characters in the article. So, at the end, I will give you the essence of this article:

Reflection is about 50 ~ slower than direct call ~ 100 times, but you will feel it only when you execute 1 million times.
To judge the performance of a function, you need to execute this function 1 million times or even 10 million times.
If you only call reflection occasionally, forget the performance impact of reflection.
If you need a large number of calls for reflection, consider caching.
Your programming philosophy is the most important factor limiting your program performance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.