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

看了 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++];
			}
		}
	}
}

你可能感兴趣的:(sun,performance)