Best performance for string to boolean conversion

后端 未结 3 1896
青春惊慌失措
青春惊慌失措 2021-01-19 13:23

Which has best performance while converting String to boolean from the below options.

  1. boolean value = new Boolean(\"true\").booleanValue();
  2. <
3条回答
  •  一生所求
    2021-01-19 13:41

    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);
    

提交回复
热议问题