Chaitanya
Chaitanya

Reputation: 356

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.

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).

Upvotes: 6

Views: 5459

Answers (5)

Sean Owen
Sean Owen

Reputation: 66886

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.

Upvotes: 0

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

The difference is

  • parseLong returns a primitive
  • new Long() will always create a new objecct

Upvotes: 7

ovunccetin
ovunccetin

Reputation: 8663

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);
}

Upvotes: 0

Maroun
Maroun

Reputation: 95958

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

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

Upvotes: 6

Amila
Amila

Reputation: 5213

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.

Upvotes: 0

Related Questions