Java中自增(++)和赋值(=)运算效率比较

时间:2023-03-09 07:15:33
Java中自增(++)和赋值(=)运算效率比较

前言

  将一个int型数组x[]从初值0变成1。有两种做法:

// 只考虑后自增
int length = x.length;
for (int i = 0; i < length; i++) {
x[i]++;
}
int length = x.length;
for (int i = 0; i < length; i++) {
x[i] = 1;
}

测试代码

/**
* @author PengHao
* @version 1.0
* @date 2019-04-30 下午6:38:02
* Environment: Windows 10
* IDE Version: Eclipse 2019-3
* JDK Version: JDK1.8.0_112
*/ public class Efficiency {
private static int LENGTH = 21474836;
private static long begin, end; /**
* @return 自增运算用时
*/
private static long autoIncrementAfter() {
int[] x = new int[LENGTH];
begin = System.currentTimeMillis(); // 当前时间
for (int i = 0; i < LENGTH; i++) {
x[i]++;
}
end = System.currentTimeMillis(); // 当前时间
return end - begin; // 循环用时
} /**
* @return 赋值运算用时
*/
private static long copyValue() {
begin = System.currentTimeMillis();
int[] x = new int[LENGTH];
for (int i = 0; i < LENGTH; i++) {
x[i] = 1;
}
end = System.currentTimeMillis();
return end - begin;
} public static void main(String[] args) {
System.out.println("LENGTH=" + LENGTH);
System.out.println("后自增用时:" + autoIncrementAfter());
System.out.println("赋值用时:" + copyValue());
}
}

运行截图

Java中自增(++)和赋值(=)运算效率比较
Java中自增(++)和赋值(=)运算效率比较
  为了严谨性(与顺序无关),将第一组数据main方法中计算顺序交换后:
Java中自增(++)和赋值(=)运算效率比较

结论

  显然,后自增要比赋值的运算效率高。数据仅供参考。


写在最后:

  1. 如需转载,请于首页至少注明链接形式的wowpH的博客这几个字;
  2. 代码原创,如需公开引用,不能删除首行注释(作者,版本号,时间等信息)。
  3. 如果有疑问欢迎评论留言,尽量解答。