reduce memory allocations

This commit is contained in:
Egor.Ushakov
2017-02-28 20:00:47 +03:00
parent 4cbae3e3a5
commit 6fd966db29
@@ -82,11 +82,14 @@ public class MethodBytecodeUtil {
private static void visit(Method method, byte[] bytecodes, MethodVisitor methodVisitor, boolean withLineNumbers) {
ReferenceType type = method.declaringType();
try {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) {
byte[] constantPool = getConstantPool(type);
try (ByteArrayBuilderOutputStream bos = new ByteArrayBuilderOutputStream(constantPool.length + 24);
DataOutputStream dos = new DataOutputStream(bos)) {
dos.writeInt(0xCAFEBABE); // magic
dos.writeInt(Opcodes.V1_8); // version
dos.writeShort(type.constantPoolCount()); // constant_pool_count
dos.write(getConstantPool(type)); // constant_pool
dos.write(constantPool); // constant_pool
dos.writeShort(0); // access_flags;
dos.writeShort(0); // this_class;
dos.writeShort(0); // super_class;
@@ -95,7 +98,7 @@ public class MethodBytecodeUtil {
dos.writeShort(0); // methods_count;
dos.writeShort(0); // attributes_count;
ClassReader reader = new ClassReader(bos.toByteArray());
ClassReader reader = new ClassReader(bos.getBuffer());
ClassWriter writer = new ClassWriter(reader, 0);
String superName = null;
@@ -291,4 +294,15 @@ public class MethodBytecodeUtil {
}
return methodRef.get();
}
private static class ByteArrayBuilderOutputStream extends ByteArrayOutputStream {
public ByteArrayBuilderOutputStream(int size) {
super(size);
}
byte[] getBuffer() {
assert buf.length == count : "Buffer is not fully filled";
return buf;
}
}
}