简体   繁体   中英

Which of these 2 algorithms is more efficient?

I was writing some code and I came up with 2 functions for wrapping around an array from the left. I named it negative modulo because it is similar to wrapping around an array from the right using modulus. I realize the performance implications are negligible on a small scale, but I would like to know which one is more efficient. What do you guys think?

static int negative_modulo(int a, int b)
    {
        int val1 = Math.Abs(a);
        if (val1 <= b)
            return b + a;
        else
            return b - (val1 % b);
    }

    static int negative_modulo2(int a, int b)
    {
        int val1 = Math.Abs(a);
        int n = val1 / b + 1;
        return a + b * n;
    }

What do you guys think?

Here's what I think ...

  1. I think you are most likely wasting your time with micro-optimizing this. In most cases, the difference in performance in code fragments like this is too small to make a significant difference to the overall performance of your program.

    It is much more important that the code works correctly. Focus on that before you spend (or waste) your time on performance.

  2. I also think that asking what people think is faster is a pointless exercise.

If you really want to know, you need to write a proper micro-benchmark, measure and compare the results. However, that writing Java micro-benchmarks that give reliable results is NOT straight-forward. Therefore you would be advised to use a framework such as Calliper for your benchmarks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM