How instanceof is implemented inside JAVA?

前端 未结 3 572
梦谈多话
梦谈多话 2021-01-13 22:05

Now I\'m writing an ORM Framework and very care about performance.

In this Framework , I have to use instanceof and Class.isAssignableFrom

3条回答
  •  长情又很酷
    2021-01-13 22:18

    1st of all, if youre going to micro-benchmark this, at least run a large loop and average, because youre seeing a lot of noise in your timing.
    having said that, yes, reflection is slow. if you can design around it and use anything else, do it.
    for example, if the set of classes you'll work with is small and known in advance, keep them in a Map and look them up there - you'll need all subclasses to be in that map, but the lookup will be much faster than an instanceof (thats basically how a lot of fast serialization libraries avoid reflection)
    if you dont want to (of cant) build this map in advance you can build it as a cache at runtime and then you'll need the instanceOf call only once per new class

提交回复
热议问题