`
berlou
  • 浏览: 1130 次
  • 来自: ...
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

蛋疼,实例对比循环的写法

阅读更多
看了http://www.iteye.com/topic/722599, 闲的蛋疼,写了个测试类看看什么情况。废话不说,上干货。以下是时间相关的性能表现。由于Jprofiler的license过期,以后有时间贴上内存和CPU开销。或者谁有空给代码弄过去跑一下对比看看。
编译和运行环境:Ecipse/Sun JDK1.6
输出结果:
VariableAndIndexInLoop-->26962812
SingleVariableIndexInLoop-->25436628
SingleVariableIndexOutLoop-->25432976
NoVariableIndexOutLoop-->24568063

结论:【请看各位精彩回帖】。

package performance;

public class Performance {

	public static void main(String[] args) {
		Strategy strategy = new VariableAndIndexInLoop();
		strategy.measure();
		strategy = new SingleVariableIndexInLoop();
		strategy.measure();
		strategy = new SingleVariableIndexOutLoop();
		strategy.measure();
		strategy = new NoVariableIndexOutLoop();
		strategy.measure();
	}
	
	static abstract class Strategy {
		static final int loop = 10000000;
		static final int[] data = new int[loop];
		static {
			for(int i = 0; i < loop;) {
				data[i++] = i; 
			}
		}
		
		protected int sum;
		
		long measure() {
			long time = System.nanoTime();
			howToDo();
			time = System.nanoTime() - time;
			System.out.println(getClass().getSimpleName() + "-->" + time);
			return time;
		}
		
		abstract void howToDo();
	}
	
	static class VariableAndIndexInLoop extends Strategy {
		void howToDo() {
			for(int i = 0; i < data.length; i++) {
				int num = data[i];
				sum += num;
			}
		}
	}
	
	static class SingleVariableIndexInLoop extends Strategy {
		void howToDo() {
			int num;
			for(int i = 0; i < data.length; i++) {
				num = data[i];
				sum += num;
			}
		}
	}
	
	static class SingleVariableIndexOutLoop extends Strategy {
		void howToDo() {
			int i, num;
			for(i = 0; i < data.length;) {
				num = data[i++];
				sum += num;
			}
		}
	}
	
	static class NoVariableIndexOutLoop extends Strategy {
		void howToDo() {
			int i;
			for(i = 0; i < data.length;) {
				sum += data[i++];
			}
		}
	}
}

分享到:
评论
1 楼 junlas 2010-07-28  
代码拷了下来,环境一致,然后就开始跑了又跑,没有统一的大小关系:如下有
VariableAndIndexInLoop-->36610481
SingleVariableIndexInLoop-->37847503
SingleVariableIndexOutLoop-->36277022
NoVariableIndexOutLoop-->49372835
==============================================
VariableAndIndexInLoop-->33454363
SingleVariableIndexInLoop-->34227380
SingleVariableIndexOutLoop-->33555574
NoVariableIndexOutLoop-->36054554


不过要是非要来个统计什么的,我就观望了

另外明显的一点是:你机器比我好。

相关推荐

Global site tag (gtag.js) - Google Analytics