Java Reflection Performance

前端 未结 14 1776
感动是毒
感动是毒 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.

提交回复
热议问题