I've been given a file with 200 fields whose values are retrieved using reflection. I've been asked to rewrite it because it's slow. The file has 200 String fields which are retrieved like this:
for (Field f : this.getClass().getFields())
{
try
{
Object o = f.get(this);
}
}
I've extrapolated the code into three classes for testing; one which uses "full" reflection, some reflection and no reflection.
"Full" reflection is the example listed above. It gets the fields, loops through them then gets the object associated with the field:
//Two hundred strings declared = "test String"
public void reflection()
throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
int count = 0;
long timer = System.nanoTime();
for (Field f : this.getClass().getFields()) {
count++;
Object o = f.get(this);
}
System.out.println(count);
System.out.print("Reflection: ");
System.out.println(System.nanoTime() - timer);
}
Less reflection involves holding putting the names of all the fields into an array and simply performing the get()
method:
//Two hundreds Strings declared = "test string"
//array holding the names of all the strings
public void reflection()
throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
int count = 0;
long timer = System.nanoTime();
for (String s : fieldnames) {
Field field = this.getClass().getField(s);
Object obj = field.get(this);
count++;
}
System.out.println(count);
System.out.print("Less reflection: ");
System.out.println(System.nanoTime() - timer);
}
The final one contains absolutely no reflection. The two hundred strings are written out and then assigned to another string when running.
//Two hundred strings declared = "test String"
public void reflection()
throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
int count = 0;
long timer = System.nanoTime();
String newVariable1 = variable1;
String newVariable2 = variable2;
//continued for all two hundred
System.out.print("No reflection: ");
System.out.println(System.nanoTime() - timer);
}
When I run "full" reflection I get: Reflection: 1511155
When I run less reflection I get: Less reflection: 1811682
and when I run no reflection I get: No reflection: 199956
While these numbers vary, the trend is the same: my results show completely the opposite of what I expected! The less reflection you use the slower it gets? Am I using System.nanoTime()
wrong? Have I been misinformed about reflection? Is the compiler playing another joke on me?
Aucun commentaire:
Enregistrer un commentaire