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

看了[url]http://www.iteye.com/topic/722599[/url], 闲的蛋疼,写了个测试类看看什么情况。废话不说,上干货。以下是时间相关的性能表现。由于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++];
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值