Java Reflection Performance

前端 未结 14 1616
感动是毒
感动是毒 2020-11-22 08:25

Does creating an object using reflection rather than calling the class constructor result in any significant performance differences?

相关标签:
14条回答
  • 2020-11-22 09:16

    Yes, it's slower.

    But remember the damn #1 rule--PREMATURE OPTIMIZATION IS THE ROOT OF ALL EVIL

    (Well, may be tied with #1 for DRY)

    I swear, if someone came up to me at work and asked me this I'd be very watchful over their code for the next few months.

    You must never optimize until you are sure you need it, until then, just write good, readable code.

    Oh, and I don't mean write stupid code either. Just be thinking about the cleanest way you can possibly do it--no copy and paste, etc. (Still be wary of stuff like inner loops and using the collection that best fits your need--Ignoring these isn't "unoptimized" programming, it's "bad" programming)

    It freaks me out when I hear questions like this, but then I forget that everyone has to go through learning all the rules themselves before they really get it. You'll get it after you've spent a man-month debugging something someone "Optimized".

    EDIT:

    An interesting thing happened in this thread. Check the #1 answer, it's an example of how powerful the compiler is at optimizing things. The test is completely invalid because the non-reflective instantiation can be completely factored out.

    Lesson? Don't EVER optimize until you've written a clean, neatly coded solution and proven it to be too slow.

    0 讨论(0)
  • 2020-11-22 09:17

    "Significant" is entirely dependent on context.

    If you're using reflection to create a single handler object based on some configuration file, and then spending the rest of your time running database queries, then it's insignificant. If you're creating large numbers of objects via reflection in a tight loop, then yes, it's significant.

    In general, design flexibility (where needed!) should drive your use of reflection, not performance. However, to determine whether performance is an issue, you need to profile rather than get arbitrary responses from a discussion forum.

    0 讨论(0)
提交回复
热议问题