Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize performance by using method handle to replace reflect #401

Open
BOFA1ex opened this issue Nov 21, 2022 · 0 comments
Open

Optimize performance by using method handle to replace reflect #401

BOFA1ex opened this issue Nov 21, 2022 · 0 comments

Comments

@BOFA1ex
Copy link

BOFA1ex commented Nov 21, 2022

RuleProxy has been sped up by caching the reflective access in v3.4.0.
However it still invokes native reflection, and there is a better way to optimize the performance :
e.g. https://github.com/FasterXML/jackson-modules-base/blob/2.15/blackbird/README.md
benchmarks https://github.com/FasterXML/jackson-modules-base/blob/2.15/blackbird/benchmarks/README.md

It could use BiConsumer to replace the ActionMethodOrderBean#method prop.
And using consumer.accept(target, actualParameters.toArray())
BTW, importing extra dependencies of method handle is needless, it's better than ASM.

static class MethodHandleRule {
    void execute(Object[] args){
        System.out.println("Using method handle as lambda.");
        System.out.println("And print args: " + Arrays.toString(args));
    }
}
    
@SuppressWarnings({"rawtypes", "unchecked"})
public void usingMethodHandle() throws Throwable {
    final MethodHandleRule target = new MethodHandleRule();
    final MethodHandles.Lookup lookup = MethodHandles.lookup();
    final Method method = target.getClass().getDeclaredMethod("execute", Object[].class);
    final MethodHandle methodHandle = lookup.unreflect(method);

    final Object functionInterface = LambdaMetafactory.metafactory(lookup, "accept",
            methodType(BiConsumer.class), methodType(void.class, Object.class, Object.class),
            methodHandle, methodHandle.type()
    ).getTarget().invoke();

    final BiConsumer consumer = (BiConsumer) functionInterface;
    final Object args = new Object[]{"123", "234"};
    consumer.accept(target, args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant