Alex Rivera | Logout

How does reflection affect Perm size?

Asked 2009-12-01T12:22:14.433
9

I have the understanding that perm size is used to store meta data, that would include byte code, static stuff etc.

My question how does usage of reflection affect the perm size, if it ever does. I mean if Program-A uses normal way of running objects and Program-B uses reflection all over, how will the perm-sizes of the two programs compare?

Edit
Report

1 Answer

3

I'm not entirely sure I understand the question but Java classes already include everything need to perform reflection on them. A .class file doesn't change based on how it's used.

Edit 1: Providing some more specific examples to better distinguish the type of "reflection" we are talking about.

Example:

class Foo {
    public void bar() {
        System.out.println( "Hello, world." );
    }
}

// Conventional calling
Foo f = new Foo();
foo.bar();

// Reflection based callling
Class fooClass = Class.forName( "Foo" );
Method m = fooClass.getMethod( "bar", null );
Object f = fooClass.newInstance();
m.invoke( m, null );     

In the conventional calling case, Foo.class and any of its direct class dependencies will be loaded. bar will be executed. The strings "Foo" and "bar" will already have been interned as part of the calling class because the byte code uses strings to resolve the classes and methods at runtime. (actually "bar" will be the full method signature so actually longer than just "bar")

In the reflection case, exactly the same thing happens. The only additional class loaded is Method.class. That should be the only affect to perm size.

The latter case has performance implications. The method look-up is relatively expensive so it's advisable to cache Method objects when you can. The extra method call to invoke has a slight performance implication as it's an extra method call. Hotspot will have trouble optimizing through this call... at least more than normal. JITing happens exactly the same.

Edit 2: Noting some additional objects that are loaded during reflection...

java.lang.Class will create and cache Method objects (or Field objects, etc.) upon access. These are cached in a SoftReference and so will be reclaimed if memory usage requires it.

However, the initialization of these objects means that there may be additional intern'ed strings loaded by the VM to

answered 2009-12-01T12:29:13.390

Your Answer