Java Double vs double:类类型vs基本类型 [英] Java Double vs double: class type vs primitive type

查看:187
本文介绍了Java Double vs double:类类型vs基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇的是Java的类和double类型的原始类型之间的性能差异。所以我创建了一个小的基准,发现类类型比原始类型慢3x-7x。 (本地机OSX上的3x,ideone上的7x)

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)

这里是测试:

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

那么为什么Double类型这么慢?为什么甚至实现了允许数学运算符?

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

推荐答案


So why is the Double type so much slower?

因为值被包装在需要分配,释放,内存管理,getter和setter的对象中b
$ b

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?

因为autobox意味着允许你使用这样的包装器,而不用担心它们不是纯值。你更喜欢不能有一个 ArrayList< Double> ?性能不总是必要,根据情况降低3x-7x的性能可能是可以接受的。

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.

在每种情况下都是这样,使用 LinkedList 随机访问元素可能是过度的,但这并不意味着 LinkedList 不应该被实现。这并不意味着对于少数随机访问使用链接列表可能会影响性能。

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.

最后一点注意:应该让VM在基准化这些事情之前热身。

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

这篇关于Java Double vs double:类类型vs基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆