/*
在进行android开发时,发现有一个很好用的代理类Proxy, 他可以截流类中的所有函数,进行加工。例如它能计算类中每个函数的执行时间。
测试结果:在遍历1万个结点时,顺序存贮耗时18ms, 而链表存贮耗时7310秒, 两者相差成千倍。
此类可以用于程序的效率优化。
不足之处:Proxy的设计框架决定了它只能支持实现接口方式的代理,不支持继承超类方式的代理,这就意味着,被代理的类必须要有接口,并且需要拦截的方法必须都在接口中进行声明。
参考资源:
http://www.ibm.com/developerworks/cn/java/j-lo-proxy1/
http://blog.youkuaiyun.com/dreamowner/archive/2009/05/13/4179259.aspx
*/
package android.Performance;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import android.os.Handler;
import android.util.Log;
public class FunCost implements InvocationHandler
{
private Object m_obj;
public static Object newInstance(Object obj)
{
Object result = (Object)Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
(InvocationHandler) new FunCost(obj));
return (result);
}
public FunCost(Object obj)
{
this.m_obj = obj;
}
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable
{
// TODO Auto-generated method stub
Object result;
try
{
Log.i("FunCost","begin method" + arg1.getName() + "-------------<");
long start = System.currentTimeMillis();
result = arg1.invoke(this.m_obj, arg2);
long end = System.currentTimeMillis();
Log.i("FunCost","the method" + arg1.getName() + " lasts " + (end - start) + "ms");
}
catch( Exception e)
{
Log.i("FunCost","unexpected Exception exception: " + e.getMessage());
throw new RuntimeException("unexpected Exception exception: " + e.getMessage());
}
finally
{
Log.i("FunCost","end method" + arg1.getName() + ">-------------");
}
return null;
}
}
//---------------------------------------------------------------------
package android.Performance;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
interface Test
{
public void testArrayList();
public void testLinkedList();
}
class Testing implements Test
{
private List m_link = new LinkedList();
private List m_array = new ArrayList();
public Testing()
{
for(int i=0; i<10000; i++)
{
m_link.add(new Integer(i));
m_array.add(new Integer(i));
}
}
public void testArrayList()
{
for(int i=0; i<10000; i++)
m_array.get(i);
}
public void testLinkedList()
{
for(int i=0; i<10000; i++)
m_link.get(i);
}
}
public class Main extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Test testing = (Test) FunCost.newInstance(new Testing());
testing.testArrayList();
testing.testLinkedList();
}
}