Skip to content

Instantly share code, notes, and snippets.

@lobster1234
Last active August 9, 2017 04:20
Show Gist options
  • Save lobster1234/8ea1b11531bbc1acae15a4e09f01d980 to your computer and use it in GitHub Desktop.
Save lobster1234/8ea1b11531bbc1acae15a4e09f01d980 to your computer and use it in GitHub Desktop.
Quick Test for reflection vs. new vs. cached
package com.marqeta.mqpay;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
System.out.println("via Reflection took " + instantiateViaReflection() + " milliseconds");
System.out.println("via New took " + instantiateAsNew() + " milliseconds");
System.out.println("via Reflection with cache took " + instantiateViaReflectionWithCache() + " milliseconds");
}
public static long instantiateViaReflection(){
long start = System.currentTimeMillis();
try {
for(int i = 0;i<1000000;i++){
Class clss = Class.forName("com.marqeta.mqpay.TestClass");
TestClass instance = (TestClass) clss.newInstance();
instance.someMethod();
}
}catch(Exception e){
e.printStackTrace();
}
return System.currentTimeMillis() - start;
}
public static long instantiateAsNew(){
long start = System.currentTimeMillis();
try {
for(int i = 0;i<1000000;i++){
TestClass instance = new TestClass();
instance.someMethod();
}
}catch(Exception e){
e.printStackTrace();
}
return System.currentTimeMillis() - start;
}
public static long instantiateViaReflectionWithCache(){
long start = System.currentTimeMillis();
Map<String, Object> cache = new HashMap();
try {
for(int i = 0;i<1000000;i++){
if(cache.containsKey("com.marqeta.mqpay.TestClass")){
((TestClass)cache.get("com.marqeta.mqpay.TestClass")).someMethod();
}else{
Class clss = Class.forName("com.marqeta.mqpay.TestClass");
TestClass instance = (TestClass) clss.newInstance();
cache.put("com.marqeta.mqpay.TestClass",instance);
instance.someMethod();
}
}
}catch(Exception e){
e.printStackTrace();
}
return System.currentTimeMillis() - start;
}
}
class TestClass{
public long someMethod(){
return System.currentTimeMillis()%10;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment