Reputation: 3998
Which of the below options has the best performance while converting string to Boolean?
boolean value = new Boolean("true").booleanValue();
boolean value = Boolean.valueOf("true");
boolean value = Boolean.parseBoolean("true");
Upvotes: 6
Views: 3203
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
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
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