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");
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);
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"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With