简体   繁体   English

Long.parseLong(String s)和new Long(String s)之间的区别?

[英]Difference between Long.parseLong(String s) and new Long(String s)?

I know that the String can be converted to a long using Long.parseLong(String) method and Long(String) constructor. 我知道可以使用Long.parseLong(String)方法和Long(String)构造函数将String转换为long。

String str="12356";
Long myvar= Long.parseLong(str);
Long myvar2 = new Long(str);

Both of them gives same output. 它们都提供相同的输出。 Value of myvar and myvar2 is same. myvar和myvar2的值相同。 I would like to know which one gives better performance and when to use parseLong and when to use new Long(String s) . 我想知道哪一个提供更好的性能以及何时使用parseLong以及何时使用新的Long(String s)

The difference is 不同的是

  • parseLong returns a primitive parseLong返回一个原语
  • new Long() will always create a new objecct new Long()将始终创建一个新的目标

new Long will always create a new object , whereas parseLong doesn't. new Long始终创建一个新对象 ,而parseLong则不会。

I advise you to go through the implementation of each one. 我建议你完成每一个的实施

If you open look at Long.java source, you can see that Long(String) actually calls parseLong(String). 如果打开Long.java源代码,可以看到Long(String)实际上调用了parseLong(String)。

The only difference is creating a new Long object. 唯一的区别是创建一个新的Long对象。 Therefore if you ignore object creation cost, they give same performance. 因此,如果忽略对象创建成本,它们会提供相同的性能。

The constructor ( new Long(String) ) calls immediately Long.parseLong(String) method. 构造函数( new Long(String) )立即调用Long.parseLong(String)方法。 So, if you use parseLong() you will omit an extra call. 因此,如果您使用parseLong()您将省略额外的调用。 However, they will give a similar performance actually. 但是,他们实际上会给出类似的表现。

The source of Java: Java的来源:

public Long(String s) throws NumberFormatException {
    this.value = parseLong(s, 10);
}

If the question really means Long myvar = Long.parseLong(str) then these are in fact identical in performance, because this line also contains a new Long creation via boxing. 如果问题确实意味着Long myvar = Long.parseLong(str)那么这些在性能上实际上是相同的,因为这一行还包含一个通过装箱的新Long创建。 parseLong() is called in both cases, and a new Long is created with its field assigned. 在两种情况下都会调用parseLong() ,并在分配了字段的情况下创建一个新的Long

If the intent was to create a long instead, which is more likely, then parseLong() is better and marginally faster for avoiding a pointless object creation. 如果意图是创建一个long ,那么更有可能,那么parseLong()更好,并且更快,以避免无意义的对象创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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