字符串到布尔值转换的最佳性能 [英] Best performance for string to boolean conversion

查看:96
本文介绍了字符串到布尔值转换的最佳性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从下面的选项中将String转换为boolean时具有最佳性能。

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


  1. boolean value = new Boolean (true)。booleanValue();

  2. boolean value = Boolean.valueOf(true);

  3. boolean value = Boolean.parseBoolean(true);

  1. boolean value = new Boolean("true").booleanValue();
  2. boolean value = Boolean.valueOf("true");
  3. boolean value = Boolean.parseBoolean("true");


推荐答案

boolean value = new Boolean("true").booleanValue();

最差,创建新的布尔对象全部时间。 BTW 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");

最好,什么都不浪费,几乎不用于原语,不涉及内存分配。 BTW所有人都委托给(Sun / Oracle):

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

如果你是偏执狂,你可以创建自己的 toBoolean (字符串名称)不忽略大小写 - 可以忽略不计:

If you are paranoid you can create your own toBoolean(String name) not ignoring case - negligibly faster:

boolean value = "true".equals(yourString);

这篇关于字符串到布尔值转换的最佳性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆