Java反射到底慢在哪?
码农突围
共 1950字,需浏览 4分钟
· 2020-09-10
点击上方“码农突围”,马上关注
这里是码农充电第一站,回复“666”,获取一份专属大礼包
真爱,请设置“星标”或点个“在看”
![](https://filescdn.proginn.com/ad0af6dc568744afa0c5e2fcb8f7890b/92f1e2be091f16960a92b10e25d206ba.webp)
反射真的存在性能问题吗?
public class ReflectionPerformanceActivity extends Activity{
private TextView mExecuteResultTxtView = null;
private EditText mExecuteCountEditTxt = null;
private Executor mPerformanceExecutor = Executors.newSingleThreadExecutor();
private static final int AVERAGE_COUNT = 10;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reflection_performance_layout);
mExecuteResultTxtView = (TextView)findViewById(R.id.executeResultTxtId);
mExecuteCountEditTxt = (EditText)findViewById(R.id.executeCountEditTxtId);
}
public void onClick(View v){
switch(v.getId()){
case R.id.executeBtnId:{
execute();
}
break;
default:{
}
break;
}
}
private void execute(){
mExecuteResultTxtView.setText("");
mPerformanceExecutor.execute(new Runnable(){
@Override
public void run(){
long costTime = 0;
int executeCount = Integer.parseInt(mExecuteCountEditTxt.getText().toString());
long reflectMethodCostTime=0,normalMethodCostTime=0,reflectFieldCostTime=0,normalFieldCostTime=0;
updateResultTextView(executeCount + "毫秒耗时情况测试");
for(int index = 0; index < AVERAGE_COUNT; index++){
updateResultTextView("第 " + (index+1) + " 次");
costTime = getNormalCallCostTime(executeCount);
reflectMethodCostTime += costTime;
updateResultTextView("执行直接调用方法耗时:" + costTime + " 毫秒");
costTime = getReflectCallMethodCostTime(executeCount);
normalMethodCostTime += costTime;
updateResultTextView("执行反射调用方法耗时:" + costTime + " 毫秒");
costTime = getNormalFieldCostTime(executeCount);
reflectFieldCostTime += costTime;
updateResultTextView("执行普通调用实例耗时:" + costTime + " 毫秒");
costTime = getReflectCallFieldCostTime(executeCount);
normalFieldCostTime += costTime;
updateResultTextView("执行反射调用实例耗时:" + costTime + " 毫秒");
}
updateResultTextView("执行直接调用方法平均耗时:" + reflectMethodCostTime/AVERAGE_COUNT + " 毫秒");
updateResultTextView("执行反射调用方法平均耗时:" + normalMethodCostTime/AVERAGE_COUNT + " 毫秒");
updateResultTextView("执行普通调用实例平均耗时:" + reflectFieldCostTime/AVERAGE_COUNT + " 毫秒");
updateResultTextView("执行反射调用实例平均耗时:" + normalFieldCostTime/AVERAGE_COUNT + " 毫秒");
}
});
}
private long getReflectCallMethodCostTime(int count){
long startTime = System.currentTimeMillis();
for(int index = 0 ; index < count; index++){
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
try{
Method setmLanguageMethod = programMonkey.getClass().getMethod("setmLanguage", String.class);
setmLanguageMethod.setAccessible(true);
setmLanguageMethod.invoke(programMonkey, "Java");
}catch(IllegalAccessException e){
e.printStackTrace();
}catch(InvocationTargetException e){
e.printStackTrace();
}catch(NoSuchMethodException e){
e.printStackTrace();
}
}
return System.currentTimeMillis()-startTime;
}
private long getReflectCallFieldCostTime(int count){
long startTime = System.currentTimeMillis();
for(int index = 0 ; index < count; index++){
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
try{
Field ageField = programMonkey.getClass().getDeclaredField("mLanguage");
ageField.set(programMonkey, "Java");
}catch(NoSuchFieldException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}
}
return System.currentTimeMillis()-startTime;
}
private long getNormalCallCostTime(int count){
long startTime = System.currentTimeMillis();
for(int index = 0 ; index < count; index++){
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
programMonkey.setmLanguage("Java");
}
return System.currentTimeMillis()-startTime;
}
private long getNormalFieldCostTime(int count){
long startTime = System.currentTimeMillis();
for(int index = 0 ; index < count; index++){
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
programMonkey.mLanguage = "Java";
}
return System.currentTimeMillis()-startTime;
}
private void updateResultTextView(final String content){
ReflectionPerformanceActivity.this.runOnUiThread(new Runnable(){
@Override
public void run(){
mExecuteResultTxtView.append(content);
mExecuteResultTxtView.append("\n");
}
});
}
}
![](https://filescdn.proginn.com/84af80d3b82e688a8f112ddee63d9a52/467a5ee521f830525a16dbaebc17c224.webp)
反射的确会导致性能问题; 反射导致的性能问题是否严重跟使用的次数有关系,如果控制在100次以内,基本上没什么差别,如果调用次数超过了100次,性能差异会很明显; 四种访问方式,直接访问实例的方式效率最高;其次是直接调用方法的方式,耗时约为直接调用实例的1.4倍;接着是通过反射访问实例的方式,耗时约为直接访问实例的3.75倍;最慢的是通过反射访问方法的方式,耗时约为直接访问实例的6.2倍;
反射到底慢在哪?
private long getReflectCallMethodCostTime(int count){
long startTime = System.currentTimeMillis();
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
Method setmLanguageMethod = null;
try{
setmLanguageMethod = programMonkey.getClass().getMethod("setmLanguage", String.class);
setmLanguageMethod.setAccessible(true);
}catch(NoSuchMethodException e){
e.printStackTrace();
}
for(int index = 0 ; index < count; index++){
try{
setmLanguageMethod.invoke(programMonkey, "Java");
}catch(IllegalAccessException e){
e.printStackTrace();
}catch(InvocationTargetException e){
e.printStackTrace();
}
}
return System.currentTimeMillis()-startTime;
}
private long getReflectCallFieldCostTime(int count){
long startTime = System.currentTimeMillis();
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
Field ageField = null;
try{
ageField = programMonkey.getClass().getDeclaredField("mLanguage");
}catch(NoSuchFieldException e){
e.printStackTrace();
}
for(int index = 0 ; index < count; index++){
try{
ageField.set(programMonkey, "Java");
}catch(IllegalAccessException e){
e.printStackTrace();
}
}
return System.currentTimeMillis()-startTime;
}
![](https://filescdn.proginn.com/fa3921d9b48f23ac617afa4ce0f07c31/5594a349653d2d172d3b664326ecaffb.webp)
private long getReflectCallMethodCostTime(int count){
long startTime = System.currentTimeMillis();
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
for(int index = 0 ; index < count; index++){
try{
Method setmLanguageMethod = programMonkey.getClass().getMethod("setmLanguage", String.class);
}catch(NoSuchMethodException e){
e.printStackTrace();
}
}
return System.currentTimeMillis()-startTime;
}
private long getReflectCallFieldCostTime(int count){
long startTime = System.currentTimeMillis();
ProgramMonkey programMonkey = new ProgramMonkey("小明", "男", 12);
for(int index = 0 ; index < count; index++){
try{
Field ageField = programMonkey.getClass().getDeclaredField("mLanguage");
}catch(NoSuchFieldException e){
e.printStackTrace();
}
}
return System.currentTimeMillis()-startTime;
}
![](https://filescdn.proginn.com/708d20246ca4aa9451c341012315b409/6fc8514174d7969961feac7e6eeaaed6.webp)
getMethod和getDeclaredField方法会比invoke和set方法耗时; 随着测试数量级越大,性能差异的比例越趋于稳定;
如果避免反射导致的性能问题?
不要过于频繁地使用反射,大量地使用反射会带来性能问题; 通过反射直接访问实例会比访问方法快很多,所以应该优先采用访问实例的方式。
后记
测试频繁调用native方法是否会有明显的性能问题; 测试同一个方法内,过多的条件判断是否会有明显的性能问题; 测试类的复杂程度是否会对反射的性能有明显影响。
最近热文
• 应届硕士被建议破格授予博士学位!这个学霸三年发了16篇SCI • 面试官写了个双冒号::问我这是什么语法?Java中有这玩意? • 亚马逊机器人公司副总离职,加入23岁华裔「天才少年」创立的AI独角兽 • 干掉 "ZooKeeper",阿里为什么不用 ZK 做服务发现? 最近整理了一份大厂算法刷题指南,包括一些刷题技巧,在知乎上已经有上万赞。同时还整理了一份6000页面试笔记。关注下面公众号,在公众号内回复「刷题」,即可免费获取!回复「加群」,可以邀请你加入读者群!
明天见(。・ω・。)ノ♡
评论