Which has best performance while converting String to boolean from the below options.
boolean value = new Boolean(\"true\").booleanValue();
boolean value = new Boolean("true").booleanValue();
Worst, creates new Boolean
objects all the time. BTW booleanValue()
is not necessary, unboxing will do it for you.
boolean value = Boolean.valueOf("true");
Much better, uses cached Boolean
instance, but performs unnecessary (although very cheap) unboxing.
boolean value = Boolean.parseBoolean("true");
Best, nothing is wasted, operates barely on primitives, no memory allocations 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 - negligibly faster:
boolean value = "true".equals(yourString);
Here is the source, looks like Tomasz beat me to answering the why:
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"));
}
The second and third one are the best options since they are static factory methods and internally the can reuse references.
Looking at 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.