faster implementation of sum ( for Codility test )

前端 未结 22 2101
鱼传尺愫
鱼传尺愫 2021-02-04 11:47

How can the following simple implementation of sum be faster?

private long sum( int [] a, int begin, int end ) {
    if( a == null   ) {
        ret         


        
22条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 12:24

    In C# 3.0, my computer and my OS this is faster as long as you can guarantee that 4 consecutive numbers won't overflow the range of an int, probably because most additions are done using 32-bit math. However using a better algorithm usually provides higher speed up than any micro-optimization.

    Time for a 100 millon elements array:

    4999912596452418 -> 233ms (sum)

    4999912596452418 -> 126ms (sum2)

        private static long sum2(int[] a, int begin, int end)
        {
            if (a == null) { return 0; }
            long r = 0;
            int i = begin;
            for (; i < end - 3; i+=4)
            {
                //int t = ;
                r += a[i] + a[i + 1] + a[i + 2] + a[i + 3];
            }
            for (; i < end; i++) { r += a[i]; }
            return r;
        }
    

提交回复
热议问题