Strange performance behaviour

Posted by plastilino on Stack Overflow See other posts from Stack Overflow or by plastilino
Published on 2010-05-16T05:29:22Z Indexed on 2010/05/16 5:40 UTC
Read the original article Hit count: 192

Filed under:
|

I'm puzzled with this.

In my machine

  • Direct calculation: 375 ms
  • Method calculation: 3594 ms, about TEN times SLOWER
  • If I place the method calulation BEFORE the direct calculation, both times are SIMILAR.

Woud you check it in your machine?

class Test {
    static long COUNT = 50000 * 10000;
    private static long BEFORE;

    /*--------METHOD---------*/
    public static final double hypotenuse(double a, double b) {
        return Math.sqrt(a * a + b * b);
    }
    /*--------TIMER---------*/
    public static void getTime(String text) {
        if (BEFORE == 0) {
            BEFORE = System.currentTimeMillis();
            return;
        }
        long now = System.currentTimeMillis();
        long elapsed = (now - BEFORE);
        BEFORE = System.currentTimeMillis();
        if (text.equals("")) {
            return;
        }
        String message = "\r\n" + text + "\r\n" + "Elapsed time: " + elapsed + " ms";
        System.out.println(message);
    }

    public static void main(String[] args) {
        double a = 0.2223221101;
        double b = 122333.167;
        getTime("");
        /*--------DIRECT CALCULATION---------*/
        for (int i = 1; i < COUNT; i++) {
            Math.sqrt(a * a + b * b);
        }
        getTime("Direct: ");
        /*--------METHOD---------*/
        for (int k = 1; k < COUNT; k++) {
            hypotenuse(a, b);
        }
        getTime("Method: ");
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about Performance