fast way to infer caller
Kasper Nielsen
kasperni at gmail.com
Thu Apr 7 11:53:33 UTC 2022
>
> MethodHandles.lookup().lookupClass() looks very promising except that
> there is no way to specify the depth.
>
> I am looking for a method to obtain the Nth caller at a cost of around
> 100 to 200 nanoseconds of CPU time. Do you think the JDK could cater
> for this use case?
>
Hi Ceki,
I don't think you will find the numbers you are looking for with
StackWalker.
Compared to something like Reflection.getCallerClass() which
MethodHandles.lookup() uses.
There is still a very large (>100x) performance gap between the two.
public class StackWalkerPerf {
static final StackWalker sw =
StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);
@Benchmark
public Class<?> stackWalkerCallerClass() {
return sw.getCallerClass();
}
@Benchmark
public Class<?> reflectionCallerClass() {
return MethodHandles.lookup().lookupClass();
}
}
Benchmark Mode Cnt Score Error Units
StackWalkerPerf.reflectionCallerClass avgt 10 2,927 ± 0,012 ns/op
StackWalkerPerf.stackWalkerCallerClass avgt 10 915,287 ± 9,565 ns/op
/Kasper
More information about the core-libs-dev
mailing list