zoukankan      html  css  js  c++  java
  • 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());
    	}
    }
    

    运行截图

      为了严谨性(与顺序无关),将第一组数据main方法中计算顺序交换后:

    结论

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


    写在最后:

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

  • 相关阅读:
    C#中的Virtual
    DevExpress控件中LayoutControl的使用
    汉字获取首字母拼音
    工具类
    C# 根据时间创建文件夹
    图片延迟加载
    IIS日志分析的作用
    SQL2008R2 无法读取此系统上以前注册的服务器的列表--网上方法不可行
    windows 服务器系统日志分析及安全
    301跳转
  • 原文地址:https://www.cnblogs.com/wowpH/p/11060803.html
Copyright © 2011-2022 走看看