user525146
user525146

Reputation: 3998

Best performance for string-to-Boolean conversion

Which of the below options has the best performance while converting string to Boolean?

  1. boolean value = new Boolean("true").booleanValue();
  2. boolean value = Boolean.valueOf("true");
  3. boolean value = Boolean.parseBoolean("true");

Upvotes: 6

Views: 3203

Answers (3)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

boolean value = new Boolean("true").booleanValue();

is the worst. It creates new Boolean objects all the time. BTW, booleanValue() is not necessary; unboxing will do it for you.

boolean value = Boolean.valueOf("true");

is much better. It uses a cached Boolean instance, but it performs unnecessary (although very cheap) unboxing.

boolean value = Boolean.parseBoolean("true");

is best. Nothing is wasted, it operates barely on primitives, and no memory allocations are involved. BTW, all of them delegate to (Sun/Oracle):

private static boolean toBoolean(String name) { 
  return ((name != null) && name.equalsIgnoreCase("true"));
}

If you are paranoid, you can create your own toBoolean(String name) not ignoring case— it is negligibly faster:

boolean value = "true".equals(yourString);

Upvotes: 22

Daniel Moses
Daniel Moses

Reputation: 5858

Here is the source:

public static Boolean valueOf(String s) {
    return toBoolean(s) ? TRUE : FALSE;
}

public static boolean parseBoolean(String s) {
    return toBoolean(s);
}

public Boolean(String s) {
    this(toBoolean(s));
}

private static boolean toBoolean(String name) {
    return ((name != null) && name.equalsIgnoreCase("true"));
}

Upvotes: 4

davidmontoyago
davidmontoyago

Reputation: 1833

The second and third one are the best options since they are static factory methods and internally they can reuse references.

Looking at the Boolean.valueOf("true") and Boolean.parseBoolean("true") implementations, they both do the same (they both call toBoolean(s);) with the difference that valueOf returns the Boxed type.

Upvotes: 2

Related Questions