简体   繁体   中英

Loading an existing java object onto stack using ASM

I am trying to use ASM for my project and hit a performance issue where I am trying to get required object using a static method and its called like 1000 times

visitor.visitMethodInsn(Opcodes.INVOKESTATIC, TrackingConstants.TO_HELPER_CLASS, "getRTTDObject",TrackingConstants.TO_HELPER_GET_CLIENT_METHOD_DESC);

visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, TrackingConstants.CLIENT_INTERFACE_CLASS, "getPattern",TrackingConstants.CLIENT_INTERFACE_CLASS_GETPATTERN_METHOD_DESC);     

This first call is causing me overhead(where I get required object and pass to next line for performing "getPattern" on the object.During investigation I realized that the object which I am trying to retrieve via the static method is available with me from the starting itself so if I was able to push that Java object onto stack and avoid the static calls I wouldn't not face any performance issues.

I tried couple of ways with no luck and finally tried to create new Field of the object but get an IllegalArgumentException similar to this post Creating a new field with asm 4 after going through the link I realized that we need write code to create the object and can't directly use existing object.

So is there no way I can load my existing Java object onto stack (I guess it will already be on stack, is there a way I can use it) and perform required operations instead of using Static call to get it? Is there a way I can achieve it?

Once the object is on the stack (presumably after you call your static method the first time), you can:

  1. Emit a DUP instruction to duplicate the value already on the stack each time it is needed. This is probably the most performant option, but it requires you to craft your bytecode in such a way that the value will always be at/near the top of the stack when you need it. There are a few variants of the DUP instruction to choose from, each with different behavior; see the JVM Specification §6.5 for details.

  2. Call the static method once, then store the result in a temporary variable (use one of the ASTORE instruction variants). Push it onto the stack when it's needed by using the corresponding ALOAD variant.

Depending on the structure of your method, you may also combine these techniques (load from a temporary local, DUP as necessary, do something unrelated, repeat, etc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM