Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

performance - Java Double vs double: class type vs primitive type

I was curious to what the performance differences between Java's class and primitive type for double were. So I created a little benchmark and found the class type to be 3x-7x slower than the primitive type. (3x on local machine OSX, 7x on ideone)

Here is the test:

class Main {
    public static void main(String args[]) {
        long bigDTime, littleDTime;

        {
            long start = System.nanoTime();
            Double d = 0.0;
            for (Double i = 0.0; i < 1432143.341; i += 0.1) {
                d += i;
            }
            long end = System.nanoTime();
            bigDTime = end - start;
            System.out.println(bigDTime);
        }

        {
            long start = System.nanoTime();
            double d = 0.0;
            for (double i = 0.0; i < 1432143.341; i += 0.1) {
                d += i;
            }
            long end = System.nanoTime();
            littleDTime = end - start;
            System.out.println(littleDTime);
        }

        System.out.println("D/d = " + (bigDTime / littleDTime));
    }
}

http://ideone.com/fDizDu

So why is the Double type so much slower? Why is it even implemented to allow mathematical operators?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

So why is the Double type so much slower?

Because the value is wrapped inside an object which needs allocation, deallocation, memory management plus getters and setters

Why is it even implemented to allow mathematical operators?

Because autobox is meant to allow you to use such wrappers without worrying about the fact that they are not plain values. Would you prefer not being able to have an ArrayList<Double>? Performance is not always necessary and a drop of 3x-7x of performance according to situations maybe acceptable. Optimization is a requirement which is not always present.

This is true in every situation, using a LinkedList to random access elements could be overkill but this doesn't mean that LinkedList shouldn't be implemented at all. This neither means that using a linked list for few random accesses could interfere with performance so much.

A final note: you should let the VM warm up before benchmarking such things.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...