其他
Java变量声明在循环体内还是循环体外,你用哪一个?
The following article is from java金融 Author java金融
来源 | java金融(ID:java4299)头图 | CSDN 下载自东方IC
引言
for (int i = 1; i <= count; i++){
Object obj = new Object();
}
Object obj = null;
for (int i = 0; i <= count; i++) {
obj = new Object();
}
效率对比
/**
* @author: 公众号【java金融】
* @Date:
* @Description:
*/
@BenchmarkMode(Mode.AverageTime) // 测试完成时间
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2) // 预热 2 轮,每次 1s
@Measurement(iterations = 5) // 测试 5 轮,每次 1s
@Fork(1) // fork 1 个线程
@State(Scope.Thread)
public class ForEachBenchMark {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(ForEachBenchMark.class.getSimpleName())
.result("result.json")
.resultFormat(ResultFormatType.JSON).build();
new Runner(opt).run();
}
@Param(value = {"10", "50", "100"})
private int length;
/**
* 循环体外创建对象
* @param blackhole
*/
@Benchmark
public void outsideLoop(Blackhole blackhole) {
Object object = null;
for (int i = 0; i < length; i++) {
object = new Object();
blackhole.consume(object);
}
}
/**
* 循环体内创建对象
* @param blackhole
*/
@Benchmark
public void insideLoop(Blackhole blackhole) {
for (int i = 0; i < length; i++) {
Object object = new Object();
blackhole.consume(object);
}
}
}
Benchmark (length) Mode Cnt Score Error Units
ForEachBenchMark.insideLoop 10 avgt 5 58.629 ± 8.857 ns/op
ForEachBenchMark.insideLoop 50 avgt 5 293.726 ± 1.856 ns/op
ForEachBenchMark.insideLoop 100 avgt 5 587.185 ± 40.424 ns/op
ForEachBenchMark.outsideLoop 10 avgt 5 59.563 ± 5.057 ns/op
ForEachBenchMark.outsideLoop 50 avgt 5 305.829 ± 27.476 ns/op
ForEachBenchMark.outsideLoop 100 avgt 5 584.853 ± 20.289 ns/op
字节码对比
public class InsideTest {
public static int count = 100;
public List<Object> insideLoop() {
List<Object> list = new ArrayList<>();
int n = 0;
for (; ; ) {
if (n > count) {
break;
}
Object o = new Object();
list.add(o);
}
Object b = 2;
return list;
}
}
public class OutsideTest {
public static int count = 100;
public List<Object> outsideLoop() {
List<Object> list = new ArrayList<>();
Object o = null;
int n = 0;
for (; ; ) {
if (n > count) {
break;
}
o = new Object();
list.add(o);
}
Object b = 2;
return list;
}
javac -g OutsideTest.java
javap -v OutsideTest.class
LocalVariableTable:
Start Length Slot Name Signature
28 8 3 o Ljava/lang/Object;
0 46 0 this Lcom/workit/autoconfigure/autoconfigure/controller/InsideTest;
8 38 1 list Ljava/util/List;
10 36 2 n I
44 2 3 b Ljava/lang/Object;
LocalVariableTable:
Start Length Slot Name Signature
0 49 0 this Lcom/workit/autoconfigure/autoconfigure/controller/OutsideTest;
8 41 1 list Ljava/util/List;
10 39 2 o Ljava/lang/Object;
12 37 3 n I
47 2 4 b Ljava/lang/Object;
总结
☞图灵奖得主 John E. Hopcroft 等 300 余位 AI 学者“穿越”回宋代开国际 AI 大会,这场面你见过吗?
☞蚂蚁上市员工人均一套大 House,阿里程序员身价和这匹配吗?
☞Robust.ai 获得 1500 万美元融资,嘴炮 Gary Marcus 也难逃真香定律