Java Reflection: Why is it so slow?

后端 未结 6 1112
独厮守ぢ
独厮守ぢ 2020-11-29 17:30

I\'ve always avoided Java reflection soley based on its reputation for slowness. I reached a point in the design of my current project where being able to use it would make

6条回答
  •  攒了一身酷
    2020-11-29 18:18

    The JITted code for instantiating B is incredibly lightweight. Basically it needs to allocate enough memory (which is just incrementing a pointer unless a GC is required) and that's about it - there's no constructor code to call really; I don't know whether the JIT skips it or not but either way there's not a lot to do.

    Compare that with everything that reflection has to do:

    • Check that there's a parameterless constructor
    • Check the accessibility of the parameterless constructor
    • Check that the caller has access to use reflection at all
    • Work out (at execution time) how much space needs to be allocated
    • Call into the constructor code (because it won't know beforehand that the constructor is empty)

    ... and probably other things I haven't even thought of.

    Typically reflection isn't used in a performance-critical context; if you need dynamic behaviour like that, you could use something like BCEL instead.

提交回复
热议问题