关于for循环的累加效率问题(java)

来源:互联网 发布:声音美化软件 编辑:程序博客网 时间:2024/04/30 01:32
累加的效率问题:
目前有下面两种方法:
方法一:
long sum = 0;
for(int i = 0;i < value;i++)
{
    sum += i;
}

方法二:
long sum = 0;
sum = (value + 1) *  value / 2;

当value值等于10000,使用方法一,运行10次有4次会产生15毫秒左右耗时,使用方法二,运行10次无耗时产生。
当value值等于100000,使用方法一,运行10次有5次会产生15毫秒左右耗时,使用方法二,运行10次无耗时产生。
当value值等于1000000,使用方法一,运行10次有10次会产生31毫秒左右耗时,使用方法二,运行10次无耗时产生。
......
以此类推,方法一累加计数的效率和方法二相比,随着value值的级数递增,效率相应下降。

测试代码:
public class SimpleArithmetic
{
    public static void main(String[] args)
    {
        SimpleArithmetic sa = new SimpleArithmetic();
        long sum = 0;
        long time = 0;
        long curTime = System.currentTimeMillis();
        System.out.println("curTime=" + curTime);
       
        //sum = sa.getSumCycle(1000000);
        sum = sa.getSumNotCycle(1000000);
        System.out.println(sum);
       
        long endTime = System.currentTimeMillis();
        System.out.println("endTime=" + endTime);
       
        time = endTime - curTime;
        System.out.println(time);
    }
   
    private long getSumCycle(long value)
    {
        long sum = 0;
       
        for(long i = 1;i <= value;i++)
        {
            sum += i;
        }
       
        return sum;
    }
   
    private long getSumNotCycle(long value)
    {
        long sum = 0;
        sum = (value + 1) * value / 2;
        return sum;
    }
}
原创粉丝点击