Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best performance for string to boolean conversion

Tags:

java

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");
like image 586
user525146 Avatar asked Nov 29 '22 09:11

user525146


2 Answers

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);
like image 183
Tomasz Nurkiewicz Avatar answered Dec 15 '22 05:12

Tomasz Nurkiewicz


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"));
}
like image 30
Daniel Moses Avatar answered Dec 15 '22 06:12

Daniel Moses