[英]Which is the difference between Long.valueOf(0) and 0L in Java?
I would like to know the difference between using Long.valueOf(0);
我想知道使用Long.valueOf(0);
之间的区别Long.valueOf(0);
or 0L
. 或0L
。 Are they the same? 它们是一样的吗?
I understand that both are Long types so they have a memory consumption of 64-bits long in Java 8. 据我所知,两者都是Long类型,所以它们在Java 8中的内存消耗为64位。
So how it is better to initialize a variable, considering memory consumption and time complexity? 那么考虑内存消耗和时间复杂度,如何更好地初始化变量呢?
Long a = Long.valueOf(0);
or 要么
Long b = 0L;
Nothing. 没有。
Long b = 0L;
will undergo autoboxing . 将进行自动装箱 。 The compiler replaces it with: 编译器将其替换为:
Long b = Long.valueOf(0L);
You can see this if you decompile your class, eg using javap
. 如果您反编译您的类,您可以看到这一点,例如使用javap
。
void a() {
Long a = Long.valueOf(0);
}
void b() {
Long b = 0L;
}
Decompiles to: 反编译为:
void a();
Code:
0: lconst_0
1: invokestatic #2 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
4: astore_1
5: return
void b();
Code:
0: lconst_0
1: invokestatic #2 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
4: astore_1
5: return
So how it is better initialize a variable, considering memory consumption and time complexity? 那么考虑内存消耗和时间复杂度,如何更好地初始化变量呢?
Because they are semantically identical, the memory consumption and time complexity is also identical. 因为它们在语义上是相同的,所以内存消耗和时间复杂度也是相同的。
Instead, focus on what is actually important, which is readability : use the one you (and others) will find most easy to understand at a glance. 相反,要关注实际上重要的东西,即可读性 :使用你(和其他人)最容易理解的那一个。
As others have pointed out, Long l = Long.valueOf(0)
and Long l = 0L
will compile to the same bytecode, the only difference is style and readability. 正如其他人所指出的, Long l = Long.valueOf(0)
和Long l = 0L
将编译为相同的字节码,唯一的区别是样式和可读性。
Additionally.. 另外..
It's a bit silly to worry about time complexity for something like this: both expressions are constant time. 担心这样的事情的时间复杂性有点傻:两个表达都是恒定的时间。 You usually only talk about time complexity when acting on collections of data not just a single piece of data. 在处理数据集合时, 通常只讨论时间复杂度,而不仅仅是单个数据。
As for memory consumption, they do not use 64 bits as you say; 至于内存消耗,它们不像你说的那样使用64位; It's the primitive long
type that typically uses 64 bits but Long
(the wrapper type) uses more memory than the primitive type because it needs that memory for object-related stuff. 它是原始的long
类型,通常使用64位但Long
(包装类型)使用的内存比原始类型多,因为它需要内存用于与对象相关的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.