6

I know that the String can be converted to a long using Long.parseLong(String) method and Long(String) constructor.

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. I would like to know which one gives better performance and when to use parseLong and when to use new Long(String s).

Chaitanya
  • 336
  • 2
  • 5
  • 13

5 Answers5

7

The difference is

  • parseLong returns a primitive
  • new Long() will always create a new objecct
yshavit
  • 42,327
  • 7
  • 87
  • 124
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
6

new Long will always create a new object, whereas parseLong doesn't.

I advise you to go through the implementation of each one.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

If you open look at Long.java source, you can see that Long(String) actually calls parseLong(String).

The only difference is creating a new Long object. Therefore if you ignore object creation cost, they give same performance.

Amila
  • 5,195
  • 1
  • 27
  • 46
0

The constructor (new Long(String)) calls immediately Long.parseLong(String) method. So, if you use parseLong() you will omit an extra call. However, they will give a similar performance actually.

The source of Java:

public Long(String s) throws NumberFormatException {
    this.value = parseLong(s, 10);
}
ovunccetin
  • 8,443
  • 5
  • 42
  • 53
0

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. parseLong() is called in both cases, and a new Long is created with its field assigned.

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.

Sean Owen
  • 66,182
  • 23
  • 141
  • 173
  • 1
    Autoboxing uses valueOf() -> http://stackoverflow.com/questions/408661/what-code-does-the-compiler-generate-for-autoboxing – Svetlin Zarev Jan 02 '14 at 08:49
  • Uses `valueOf(long)`, yes. My point is that either way you have all but identical operations: `new Long` which does `this.value = value`, and a call to `parseLong`. – Sean Owen Jan 02 '14 at 09:26
  • ... although if you're getting at the fact that `valueOf(long)` caches -128L to 127L, yeah that would be a difference and slight reason to prefer the boxing. – Sean Owen Jan 02 '14 at 09:28