2019年12月20日 | Leave a comment https://mp.weixin.qq.com/s?__biz=MzIzOTU0NTQ0MA==&mid=2247492922&idx=1&sn=129283d4c520da6204f696ce86c15b2c&chksm=e92ad835de5d5123280d0c527301728da7d05986e8d7ac814e388928ebd47994906267f42c01&token=1952579014&lang=zh_CN&scene=21#wechat_redirect 1.常量&变量 1.1.直接赋值常量值,禁止声明新对象 直接赋值常量值,只是创建了一个对象引用,而这个对象引用指向常量值。 反例: <span class="code-snippet_outer">Long i = new Long(1L);</span></code><code><span class="code-snippet_outer">String s = new String("abc");</span> 1 <span class="code-snippet_outer">Long i = new Long(1L);</span></code><code><span class="code-snippet_outer">String s = new String("abc");</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__attribute">Long</span> i = 1L;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__attribute">String</span> s = <span class="code-snippet__string">"abc"</span>;</span> 1 <span class="code-snippet_outer"><span class="code-snippet__attribute">Long</span> i = 1L;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__attribute">String</span> s = <span class="code-snippet__string">"abc"</span>;</span> 1.2.当成员变量值无需改变时,尽量定义为静态常量 在类的每个对象实例中,每个成员变量都有一份副本,而成员静态常量只有一份实例。 反例: <span class="code-snippet_outer">public class HttpConnection {</span></code><code><span class="code-snippet_outer"> private final long timeout = 5L;</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public class HttpConnection {</span></code><code><span class="code-snippet_outer"> private final long timeout = 5L;</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public class HttpConnection {</span></code><code><span class="code-snippet_outer"> private static final long TIMEOUT = 5L;</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public class HttpConnection {</span></code><code><span class="code-snippet_outer"> private static final long TIMEOUT = 5L;</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1.3.尽量使用基本数据类型,避免自动装箱和拆箱 Java 中的基本数据类型double、float、long、int、short、char、boolean,分别对应包装类Double、Float、Long、Integer、Short、Character、Boolean。JVM支持基本类型与对应包装类的自动转换,被称为自动装箱和拆箱。装箱和拆箱都是需要CPU和内存资源的,所以应尽量避免使用自动装箱和拆箱。 反例: <span class="code-snippet_outer">Integer sum = <span class="code-snippet__number">0</span>;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">int</span>[] values = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (<span class="code-snippet__keyword">int</span> <span class="code-snippet__keyword">value</span> : values) {</span></code><code><span class="code-snippet_outer"> sum += <span class="code-snippet__keyword">value</span>; <span class="code-snippet__comment">// 相当于result = Integer.valueOf(result.intValue() + value);</span></span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">Integer sum = <span class="code-snippet__number">0</span>;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">int</span>[] values = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (<span class="code-snippet__keyword">int</span> <span class="code-snippet__keyword">value</span> : values) {</span></code><code><span class="code-snippet_outer"> sum += <span class="code-snippet__keyword">value</span>; <span class="code-snippet__comment">// 相当于result = Integer.valueOf(result.intValue() + value);</span></span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">int sum = 0;</span></code><code><span class="code-snippet_outer">int[] values = ...;</span></code><code><span class="code-snippet_outer">for (int value : values) {</span></code><code><span class="code-snippet_outer"> sum += value;</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">int sum = 0;</span></code><code><span class="code-snippet_outer">int[] values = ...;</span></code><code><span class="code-snippet_outer">for (int value : values) {</span></code><code><span class="code-snippet_outer"> sum += value;</span></code><code><span class="code-snippet_outer">}</span> 1.4.如果变量的初值会被覆盖,就没有必要给变量赋初值 反例: <span class="code-snippet_outer">List<UserDO> userList = new ArrayList<>();</span></code><code><span class="code-snippet_outer">if (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">} else {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userList = new ArrayList<>();</span></code><code><span class="code-snippet_outer">if (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">} else {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<UserDO> userList;</span></code><code><span class="code-snippet_outer">if (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">} else {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userList;</span></code><code><span class="code-snippet_outer">if (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">} else {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">}</span> 1.5.尽量使用函数内的基本类型临时变量 在函数内,基本类型的参数和临时变量都保存在栈(Stack)中,访问速度较快;对象类型的参数和临时变量的引用都保存在栈(Stack)中,内容都保存在堆(Heap)中,访问速度较慢。在类中,任何类型的成员变量都保存在堆(Heap)中,访问速度较慢。 反例: <span class="code-snippet_outer">public final class Accumulator {</span></code><code><span class="code-snippet_outer"> private double result = 0.0D;</span></code><code><span class="code-snippet_outer"> public void addAll(@NonNull double[] values) {</span></code><code><span class="code-snippet_outer"> for(double value : values) {</span></code><code><span class="code-snippet_outer"> result += value;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public final class Accumulator {</span></code><code><span class="code-snippet_outer"> private double result = 0.0D;</span></code><code><span class="code-snippet_outer"> public void addAll(@NonNull double[] values) {</span></code><code><span class="code-snippet_outer"> for(double value : values) {</span></code><code><span class="code-snippet_outer"> result += value;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public final class Accumulator {</span></code><code><span class="code-snippet_outer"> private double result = 0.0D;</span></code><code><span class="code-snippet_outer"> public void addAll(@NonNull double[] values) {</span></code><code><span class="code-snippet_outer"> double sum = 0.0D;</span></code><code><span class="code-snippet_outer"> for(double value : values) {</span></code><code><span class="code-snippet_outer"> sum += value;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> result += sum;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public final class Accumulator {</span></code><code><span class="code-snippet_outer"> private double result = 0.0D;</span></code><code><span class="code-snippet_outer"> public void addAll(@NonNull double[] values) {</span></code><code><span class="code-snippet_outer"> double sum = 0.0D;</span></code><code><span class="code-snippet_outer"> for(double value : values) {</span></code><code><span class="code-snippet_outer"> sum += value;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> result += sum;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1.6.尽量不要在循环体外定义变量 在老版JDK中,建议“尽量不要在循环体内定义变量”,但是在新版的JDK中已经做了优化。通过对编译后的字节码分析,变量定义在循环体外和循环体内没有本质的区别,运行效率基本上是一样的。 反而,根据“ 局部变量作用域最小化 ”原则,变量定义在循环体内更科学更便于维护,避免了延长大对象生命周期导致延缓回收问题 。 反例: <span class="code-snippet_outer">UserVO userVO;</span></code><code><span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">UserVO userVO;</span></code><code><span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 1.7.不可变的静态常量,尽量使用非线程安全类 不可变的静态常量,虽然需要支持多线程访问,也可以使用非线程安全类。 反例: <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP;</span></code><code><span class="code-snippet_outer">static {</span></code><code><span class="code-snippet_outer"> Map<String, Class> classMap = new ConcurrentHashMap<>(16);</span></code><code><span class="code-snippet_outer"> classMap.put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> CLASS_MAP = Collections.unmodifiableMap(classMap);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP;</span></code><code><span class="code-snippet_outer">static {</span></code><code><span class="code-snippet_outer"> Map<String, Class> classMap = new ConcurrentHashMap<>(16);</span></code><code><span class="code-snippet_outer"> classMap.put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> CLASS_MAP = Collections.unmodifiableMap(classMap);</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP;</span></code><code><span class="code-snippet_outer">static {</span></code><code><span class="code-snippet_outer"> Map<String, Class> classMap = new HashMap<>(16);</span></code><code><span class="code-snippet_outer"> classMap.put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> CLASS_MAP = Collections.unmodifiableMap(classMap);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP;</span></code><code><span class="code-snippet_outer">static {</span></code><code><span class="code-snippet_outer"> Map<String, Class> classMap = new HashMap<>(16);</span></code><code><span class="code-snippet_outer"> classMap.put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> CLASS_MAP = Collections.unmodifiableMap(classMap);</span></code><code><span class="code-snippet_outer">}</span> 1.8.不可变的成员变量,尽量使用非线程安全类 不可变的成员变量,虽然需要支持多线程访问,也可以使用非线程安全类。 反例: <span class="code-snippet_outer">@Service</span></code><code><span class="code-snippet_outer">public class StrategyFactory implements InitializingBean {</span></code><code><span class="code-snippet_outer"> @Autowired</span></code><code><span class="code-snippet_outer"> private List<Strategy> strategyList;</span></code><code><span class="code-snippet_outer"> private Map<String, Strategy> strategyMap;</span></code><code><span class="code-snippet_outer"> @Override</span></code><code><span class="code-snippet_outer"> public void afterPropertiesSet() {</span></code><code><span class="code-snippet_outer"> if (CollectionUtils.isNotEmpty(strategyList)) {</span></code><code><span class="code-snippet_outer"> int size = (int) Math.ceil(strategyList.size() * 4.0 / 3);</span></code><code><span class="code-snippet_outer"> Map<String, Strategy> map = new ConcurrentHashMap<>(size);</span></code><code><span class="code-snippet_outer"> for (Strategy strategy : strategyList) {</span></code><code><span class="code-snippet_outer"> map.put(strategy.getType(), strategy);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> strategyMap = Collections.unmodifiableMap(map);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">@Service</span></code><code><span class="code-snippet_outer">public class StrategyFactory implements InitializingBean {</span></code><code><span class="code-snippet_outer"> @Autowired</span></code><code><span class="code-snippet_outer"> private List<Strategy> strategyList;</span></code><code><span class="code-snippet_outer"> private Map<String, Strategy> strategyMap;</span></code><code><span class="code-snippet_outer"> @Override</span></code><code><span class="code-snippet_outer"> public void afterPropertiesSet() {</span></code><code><span class="code-snippet_outer"> if (CollectionUtils.isNotEmpty(strategyList)) {</span></code><code><span class="code-snippet_outer"> int size = (int) Math.ceil(strategyList.size() * 4.0 / 3);</span></code><code><span class="code-snippet_outer"> Map<String, Strategy> map = new ConcurrentHashMap<>(size);</span></code><code><span class="code-snippet_outer"> for (Strategy strategy : strategyList) {</span></code><code><span class="code-snippet_outer"> map.put(strategy.getType(), strategy);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> strategyMap = Collections.unmodifiableMap(map);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">@Service</span></code><code><span class="code-snippet_outer">public class StrategyFactory implements InitializingBean {</span></code><code><span class="code-snippet_outer"> @Autowired</span></code><code><span class="code-snippet_outer"> private List<Strategy> strategyList;</span></code><code><span class="code-snippet_outer"> private Map<String, Strategy> strategyMap;</span></code><code><span class="code-snippet_outer"> @Override</span></code><code><span class="code-snippet_outer"> public void afterPropertiesSet() {</span></code><code><span class="code-snippet_outer"> if (CollectionUtils.isNotEmpty(strategyList)) {</span></code><code><span class="code-snippet_outer"> int size = (int) Math.ceil(strategyList.size() * 4.0 / 3);</span></code><code><span class="code-snippet_outer"> Map<String, Strategy> map = new HashMap<>(size);</span></code><code><span class="code-snippet_outer"> for (Strategy strategy : strategyList) {</span></code><code><span class="code-snippet_outer"> map.put(strategy.getType(), strategy);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> strategyMap = Collections.unmodifiableMap(map);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span> 1 <span class="code-snippet_outer">@Service</span></code><code><span class="code-snippet_outer">public class StrategyFactory implements InitializingBean {</span></code><code><span class="code-snippet_outer"> @Autowired</span></code><code><span class="code-snippet_outer"> private List<Strategy> strategyList;</span></code><code><span class="code-snippet_outer"> private Map<String, Strategy> strategyMap;</span></code><code><span class="code-snippet_outer"> @Override</span></code><code><span class="code-snippet_outer"> public void afterPropertiesSet() {</span></code><code><span class="code-snippet_outer"> if (CollectionUtils.isNotEmpty(strategyList)) {</span></code><code><span class="code-snippet_outer"> int size = (int) Math.ceil(strategyList.size() * 4.0 / 3);</span></code><code><span class="code-snippet_outer"> Map<String, Strategy> map = new HashMap<>(size);</span></code><code><span class="code-snippet_outer"> for (Strategy strategy : strategyList) {</span></code><code><span class="code-snippet_outer"> map.put(strategy.getType(), strategy);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> strategyMap = Collections.unmodifiableMap(map);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span> 2.对象&类 2.1.禁止使用JSON转化对象 JSON提供把对象转化为JSON字符串、把JSON字符串转为对象的功能,于是被某些人用来转化对象。这种对象转化方式,虽然在功能上没有问题,但是在性能上却存在问题。 反例: <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = JSON.parseArray(JSON.toJSONString(userDOList), UserVO.class);</span> 1 <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = JSON.parseArray(JSON.toJSONString(userDOList), UserVO.class);</span> 正例: <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 2.2.尽量不使用反射赋值对象 用反射赋值对象,主要优点是节省了代码量,主要缺点却是性能有所下降。 反例: <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> BeanUtils.copyProperties(userDO, userVO);</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> BeanUtils.copyProperties(userDO, userVO);</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(userDO.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> userVOList.add(userVO);</span></code><code><span class="code-snippet_outer">}</span> 2.3.采用Lambda表达式替换内部匿名类 对于大多数刚接触JDK8的同学来说,都会认为Lambda表达式就是匿名内部类的语法糖。实际上, Lambda表达式在大多数虚拟机中采用invokeDynamic指令实现,相对于匿名内部类在效率上会更高一些。 反例: <span class="code-snippet_outer">List<User> userList = ...;</span></code><code><span class="code-snippet_outer">Collections.sort(userList, new Comparator<User>() {</span></code><code><span class="code-snippet_outer"> @Override</span></code><code><span class="code-snippet_outer"> public int compare(User user1, User user2) {</span></code><code><span class="code-snippet_outer"> Long userId1 = user1.getId();</span></code><code><span class="code-snippet_outer"> Long userId2 = user2.getId();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> return userId1.compareTo(userId2);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">});</span> 1 <span class="code-snippet_outer">List<User> userList = ...;</span></code><code><span class="code-snippet_outer">Collections.sort(userList, new Comparator<User>() {</span></code><code><span class="code-snippet_outer"> @Override</span></code><code><span class="code-snippet_outer"> public int compare(User user1, User user2) {</span></code><code><span class="code-snippet_outer"> Long userId1 = user1.getId();</span></code><code><span class="code-snippet_outer"> Long userId2 = user2.getId();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> return userId1.compareTo(userId2);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">});</span> 正例: <span class="code-snippet_outer">List<User> userList = ...;</span></code><code><span class="code-snippet_outer">Collections.sort(userList, (user1, user2) -> {</span></code><code><span class="code-snippet_outer"> Long userId1 = user1.getId();</span></code><code><span class="code-snippet_outer"> Long userId2 = user2.getId();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> return userId1.compareTo(userId2);</span></code><code><span class="code-snippet_outer">});</span> 1 <span class="code-snippet_outer">List<User> userList = ...;</span></code><code><span class="code-snippet_outer">Collections.sort(userList, (user1, user2) -> {</span></code><code><span class="code-snippet_outer"> Long userId1 = user1.getId();</span></code><code><span class="code-snippet_outer"> Long userId2 = user2.getId();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> return userId1.compareTo(userId2);</span></code><code><span class="code-snippet_outer">});</span> 2.4.尽量避免定义不必要的子类 多一个类就需要多一份类加载,所以尽量避免定义不必要的子类。 反例: <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP =</span></code><code><span class="code-snippet_outer"> Collections.unmodifiableMap(new HashMap<String, Class>(16) {</span></code><code><span class="code-snippet_outer"> private static final long serialVersionUID = 1L;</span></code><code><span class="code-snippet_outer"> {</span></code><code><span class="code-snippet_outer"> put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">});</span> 1 <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP =</span></code><code><span class="code-snippet_outer"> Collections.unmodifiableMap(new HashMap<String, Class>(16) {</span></code><code><span class="code-snippet_outer"> private static final long serialVersionUID = 1L;</span></code><code><span class="code-snippet_outer"> {</span></code><code><span class="code-snippet_outer"> put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">});</span> 正例: <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP;</span></code><code><span class="code-snippet_outer">static {</span></code><code><span class="code-snippet_outer"> Map<String, Class> classMap = new HashMap<>(16);</span></code><code><span class="code-snippet_outer"> classMap.put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> CLASS_MAP = Collections.unmodifiableMap(classMap);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public static final Map<String, Class> CLASS_MAP;</span></code><code><span class="code-snippet_outer">static {</span></code><code><span class="code-snippet_outer"> Map<String, Class> classMap = new HashMap<>(16);</span></code><code><span class="code-snippet_outer"> classMap.put("VARCHAR", java.lang.String.class);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> CLASS_MAP = Collections.unmodifiableMap(classMap);</span></code><code><span class="code-snippet_outer">}</span> 2.5.尽量指定类的final修饰符 为类指定final修饰符,可以让该类不可以被继承。如果指定了一个类为final,则该类所有的方法都是final的,Java编译器会寻找机会内联所有的final方法。内联对于提升Java运行效率作用重大,具体可参见Java运行期优化,能够使性能平均提高50%。 反例: <span class="code-snippet_outer">public class DateHelper {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public class DateHelper {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public final class DateHelper {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public final class DateHelper {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 注意:使用Spring的AOP特性时,需要对Bean进行动态代理,如果Bean类添加了final修饰,会导致异常。 3.方法 3.1.把跟类成员变量无关的方法声明成静态方法 静态方法的好处就是不用生成类的实例就可以直接调用。静态方法不再属于某个对象,而是属于它所在的类。只需要通过其类名就可以访问,不需要再消耗资源去反复创建对象。即便在类内部的私有方法,如果没有使用到类成员变量,也应该声明为静态方法。 反例: <span class="code-snippet_outer">public int getMonth(Date date) {</span></code><code><span class="code-snippet_outer"> Calendar calendar = Calendar.getInstance();</span></code><code><span class="code-snippet_outer"> calendar.setTime(date);</span></code><code><span class="code-snippet_outer"> return calendar.get(Calendar.MONTH) + 1;</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public int getMonth(Date date) {</span></code><code><span class="code-snippet_outer"> Calendar calendar = Calendar.getInstance();</span></code><code><span class="code-snippet_outer"> calendar.setTime(date);</span></code><code><span class="code-snippet_outer"> return calendar.get(Calendar.MONTH) + 1;</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public static int getMonth(Date date) {</span></code><code><span class="code-snippet_outer"> Calendar calendar = Calendar.getInstance();</span></code><code><span class="code-snippet_outer"> calendar.setTime(date);</span></code><code><span class="code-snippet_outer"> return calendar.get(Calendar.MONTH) + 1;</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public static int getMonth(Date date) {</span></code><code><span class="code-snippet_outer"> Calendar calendar = Calendar.getInstance();</span></code><code><span class="code-snippet_outer"> calendar.setTime(date);</span></code><code><span class="code-snippet_outer"> return calendar.get(Calendar.MONTH) + 1;</span></code><code><span class="code-snippet_outer">}</span> 3.2.尽量使用基本数据类型作为方法参数类型,避免不必要的装箱、拆箱和空指针判断 反例: <span class="code-snippet_outer">public static double sum(Double value1, Double value2) {</span></code><code><span class="code-snippet_outer"> double double1 = Objects.isNull(value1) ? 0.0D : value1;</span></code><code><span class="code-snippet_outer"> double double2 = Objects.isNull(value2) ? 0.0D : value2;</span></code><code><span class="code-snippet_outer"> return double1 + double2;</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">double result = sum(1.0D, 2.0D);</span> 1 <span class="code-snippet_outer">public static double sum(Double value1, Double value2) {</span></code><code><span class="code-snippet_outer"> double double1 = Objects.isNull(value1) ? 0.0D : value1;</span></code><code><span class="code-snippet_outer"> double double2 = Objects.isNull(value2) ? 0.0D : value2;</span></code><code><span class="code-snippet_outer"> return double1 + double2;</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">double result = sum(1.0D, 2.0D);</span> 正例: <span class="code-snippet_outer">public static double sum(double value1, double value2) {</span></code><code><span class="code-snippet_outer"> return value1 + value2;</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">double result = sum(1.0D, 2.0D);</span> 1 <span class="code-snippet_outer">public static double sum(double value1, double value2) {</span></code><code><span class="code-snippet_outer"> return value1 + value2;</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">double result = sum(1.0D, 2.0D);</span> 3.3.尽量使用基本数据类型作为方法返回值类型,避免不必要的装箱、拆箱和空指针判断 在JDK类库的方法中,很多方法返回值都采用了基本数据类型,首先是为了避免不必要的装箱和拆箱,其次是为了避免返回值的空指针判断。比如:Collection.isEmpty()和Map.size()。 反例: <span class="code-snippet_outer">public static Boolean isValid(UserDO user) {</span></code><code><span class="code-snippet_outer"> if (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> return false;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span></code><code> </code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">Boolean isValid = isValid(user);</span></code><code><span class="code-snippet_outer">if (Objects.nonNull(isValid) && isValid.booleanValue()) { </span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 12 <span class="code-snippet_outer">public static Boolean isValid(UserDO user) {</span></code><code><span class="code-snippet_outer"> if (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> return false;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span></code><code></code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">Boolean isValid = isValid(user);</span></code><code><span class="code-snippet_outer">if (Objects.nonNull(isValid) && isValid.booleanValue()) { </span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public static boolean isValid(UserDO user) {</span></code><code><span class="code-snippet_outer"> if (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> return false;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span></code><code> </code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">if (isValid(user)) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 12 <span class="code-snippet_outer">public static boolean isValid(UserDO user) {</span></code><code><span class="code-snippet_outer"> if (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> return false;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span></code><code></code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">if (isValid(user)) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 3.4.协议方法参数值非空,避免不必要的空指针判断 协议编程,可以@NonNull和@Nullable标注参数,是否遵循全凭调用者自觉。 反例: <span class="code-snippet_outer">public static boolean isValid(UserDO user) {</span></code><code><span class="code-snippet_outer"> if (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> return false;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public static boolean isValid(UserDO user) {</span></code><code><span class="code-snippet_outer"> if (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> return false;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public static boolean isValid(@NonNull UserDO user) {</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public static boolean isValid(@NonNull UserDO user) {</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span> 3.5.协议方法返回值非空,避免不必要的空指针判断 协议编程,可以@NonNull和@Nullable标注参数,是否遵循全凭实现者自觉。 反例: <span class="code-snippet_outer">// 定义接口</span></code><code><span class="code-snippet_outer">public interface OrderService {</span></code><code><span class="code-snippet_outer"> public List<OrderVO> queryUserOrder(Long userId);</span></code><code><span class="code-snippet_outer">}</span></code><code> </code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">List<OrderVO> orderList = orderService.queryUserOrder(userId);</span></code><code><span class="code-snippet_outer">if (CollectionUtils.isNotEmpty(orderList)) {</span></code><code><span class="code-snippet_outer"> for (OrderVO order : orderList) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 12 <span class="code-snippet_outer">// 定义接口</span></code><code><span class="code-snippet_outer">public interface OrderService {</span></code><code><span class="code-snippet_outer"> public List<OrderVO> queryUserOrder(Long userId);</span></code><code><span class="code-snippet_outer">}</span></code><code></code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">List<OrderVO> orderList = orderService.queryUserOrder(userId);</span></code><code><span class="code-snippet_outer">if (CollectionUtils.isNotEmpty(orderList)) {</span></code><code><span class="code-snippet_outer"> for (OrderVO order : orderList) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">// 定义接口</span></code><code><span class="code-snippet_outer">public interface OrderService {</span></code><code><span class="code-snippet_outer"> @NonNull</span></code><code><span class="code-snippet_outer"> public List<OrderVO> queryUserOrder(Long userId);</span></code><code><span class="code-snippet_outer">}</span></code><code> </code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">List<OrderVO> orderList = orderService.queryUserOrder(userId);</span></code><code><span class="code-snippet_outer">for (OrderVO order : orderList) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 12 <span class="code-snippet_outer">// 定义接口</span></code><code><span class="code-snippet_outer">public interface OrderService {</span></code><code><span class="code-snippet_outer"> @NonNull</span></code><code><span class="code-snippet_outer"> public List<OrderVO> queryUserOrder(Long userId);</span></code><code><span class="code-snippet_outer">}</span></code><code></code><code><span class="code-snippet_outer">// 调用代码</span></code><code><span class="code-snippet_outer">List<OrderVO> orderList = orderService.queryUserOrder(userId);</span></code><code><span class="code-snippet_outer">for (OrderVO order : orderList) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 3.6.被调用方法已支持判空处理,调用方法无需再进行判空处理 反例: <span class="code-snippet_outer">UserDO user = null;</span></code><code><span class="code-snippet_outer">if (StringUtils.isNotBlank(value)) {</span></code><code><span class="code-snippet_outer"> user = JSON.parseObject(value, UserDO.class);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">UserDO user = null;</span></code><code><span class="code-snippet_outer">if (StringUtils.isNotBlank(value)) {</span></code><code><span class="code-snippet_outer"> user = JSON.parseObject(value, UserDO.class);</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">UserDO user = <span class="code-snippet__built_in">JSON</span>.parseObject(value, UserDO.class);</span> 1 <span class="code-snippet_outer">UserDO user = <span class="code-snippet__built_in">JSON</span>.parseObject(value, UserDO.class);</span> 3.7.尽量避免不必要的函数封装 方法调用会引起入栈和出栈,导致消耗更多的CPU和内存,应当尽量避免不必要的函数封装。当然,为了使代码更简洁、更清晰、更易维护,增加一定的方法调用所带来的性能损耗是值得的。 反例: <span class="code-snippet_outer">// 函数封装</span></code><code><span class="code-snippet_outer">public static boolean isVip(Boolean isVip) {</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(isVip);</span></code><code><span class="code-snippet_outer">}</span></code><code> </code><code><span class="code-snippet_outer">// 使用代码</span></code><code><span class="code-snippet_outer">boolean isVip = isVip(user.getVip());</span> 12 <span class="code-snippet_outer">// 函数封装</span></code><code><span class="code-snippet_outer">public static boolean isVip(Boolean isVip) {</span></code><code><span class="code-snippet_outer"> return Boolean.TRUE.equals(isVip);</span></code><code><span class="code-snippet_outer">}</span></code><code></code><code><span class="code-snippet_outer">// 使用代码</span></code><code><span class="code-snippet_outer">boolean isVip = isVip(user.getVip());</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__built_in">boolean</span> isVip = <span class="code-snippet__built_in">Boolean</span>.TRUE.equals(user.getVip());</span> 1 <span class="code-snippet_outer"><span class="code-snippet__built_in">boolean</span> isVip = <span class="code-snippet__built_in">Boolean</span>.TRUE.equals(user.getVip());</span> 3.8.尽量指定方法的final修饰符 方法指定final修饰符,可以让方法不可以被重写,Java编译器会寻找机会内联所有的final方法。内联对于提升Java运行效率作用重大,具体可参见Java运行期优化,能够使性能平均提高50%。 注意:所有的private方法会隐式地被指定final修饰符,所以无须再为其指定final修饰符。 反例: <span class="code-snippet_outer">public class Rectangle {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> public double area() {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public class Rectangle {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> public double area() {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">public class Rectangle {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> public final double area() {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public class Rectangle {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> public final double area() {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 注意:使用Spring的AOP特性时,需要对Bean进行动态代理,如果方法添加了final修饰,将不会被代理。 4.表达式 4.1.尽量减少方法的重复调用 反例: <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">for (int i = 0; i < userList.size(); i++) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">for (int i = 0; i < userList.size(); i++) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">int userLength = userList.size();</span></code><code><span class="code-snippet_outer">for (int i = 0; i < userLength; i++) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">int userLength = userList.size();</span></code><code><span class="code-snippet_outer">for (int i = 0; i < userLength; i++) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 4.2.尽量避免不必要的方法调用 反例: <span class="code-snippet_outer">List<UserDO> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">if (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">if (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><UserDO> userList;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">if</span> (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">} <span class="code-snippet__keyword">else</span> {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><UserDO> userList;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">if</span> (isAll) {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryAll();</span></code><code><span class="code-snippet_outer">} <span class="code-snippet__keyword">else</span> {</span></code><code><span class="code-snippet_outer"> userList = userDAO.queryActive();</span></code><code><span class="code-snippet_outer">}</span> 4.3.尽量使用移位来代替正整数乘除 用移位操作可以极大地提高性能。对于乘除2^n(n为正整数)的正整数计算,可以用移位操作来代替。 反例: <span class="code-snippet_outer">int num1 = a * 4;</span></code><code><span class="code-snippet_outer">int num2 = a / 4;</span> 1 <span class="code-snippet_outer">int num1 = a * 4;</span></code><code><span class="code-snippet_outer">int num2 = a / 4;</span> 正例: <span class="code-snippet_outer">int num1 = a << 2;</span></code><code><span class="code-snippet_outer">int num2 = a >> 2;</span> 1 <span class="code-snippet_outer">int num1 = a << 2;</span></code><code><span class="code-snippet_outer">int num2 = a >> 2;</span> 4.4.提取公共表达式,避免重复计算 提取公共表达式,只计算一次值,然后重复利用值。 反例: <span class="code-snippet_outer">double distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));</span> 1 <span class="code-snippet_outer">double distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> dx = x2 - x1;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> dy = y2 - y1;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> distance = Math.<span class="code-snippet__built_in">sqrt</span>(dx * dx + dy * dy);</span></code><code><span class="code-snippet_outer">或</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> distance = Math.<span class="code-snippet__built_in">sqrt</span>(Math.<span class="code-snippet__built_in">pow</span>(x2 - x1, <span class="code-snippet__number">2</span>) + Math.<span class="code-snippet__built_in">pow</span>(y2 - y1, <span class="code-snippet__number">2</span>));</span> 1 <span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> dx = x2 - x1;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> dy = y2 - y1;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> distance = Math.<span class="code-snippet__built_in">sqrt</span>(dx * dx + dy * dy);</span></code><code><span class="code-snippet_outer">或</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">double</span> distance = Math.<span class="code-snippet__built_in">sqrt</span>(Math.<span class="code-snippet__built_in">pow</span>(x2 - x1, <span class="code-snippet__number">2</span>) + Math.<span class="code-snippet__built_in">pow</span>(y2 - y1, <span class="code-snippet__number">2</span>));</span> 4.5.尽量不在条件表达式中用!取反 使用!取反会多一次计算,如果没有必要则优化掉。 反例: <span class="code-snippet_outer"><span class="code-snippet__keyword">if</span> (!(a >= <span class="code-snippet__number">10</span>)) {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理1</span></span></code><code><span class="code-snippet_outer">} <span class="code-snippet__keyword">else</span> {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理2</span></span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__keyword">if</span> (!(a >= <span class="code-snippet__number">10</span>)) {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理1</span></span></code><code><span class="code-snippet_outer">} <span class="code-snippet__keyword">else</span> {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理2</span></span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__keyword">if</span> (a < <span class="code-snippet__number">10</span>) {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理1</span></span></code><code><span class="code-snippet_outer">} <span class="code-snippet__keyword">else</span> {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理2</span></span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__keyword">if</span> (a < <span class="code-snippet__number">10</span>) {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理1</span></span></code><code><span class="code-snippet_outer">} <span class="code-snippet__keyword">else</span> {</span></code><code><span class="code-snippet_outer"> ... <span class="code-snippet__comment">// 条件处理2</span></span></code><code><span class="code-snippet_outer">}</span> 4.6.对于多常量选择分支,尽量使用switch语句而不是if-else语句 if-else语句,每个if条件语句都要加装计算,直到if条件语句为true为止。switch语句进行了跳转优化,Java中采用tableswitch或lookupswitch指令实现,对于多常量选择分支处理效率更高。经过试验证明:在每个分支出现概率相同的情况下,低于5个分支时if-else语句效率更高,高于5个分支时switch语句效率更高。 反例: <span class="code-snippet_outer">if (i == 1) {</span></code><code><span class="code-snippet_outer"> ...; // 分支1</span></code><code><span class="code-snippet_outer">} else if (i == 2) {</span></code><code><span class="code-snippet_outer"> ...; // 分支2</span></code><code><span class="code-snippet_outer">} else if (i == ...) {</span></code><code><span class="code-snippet_outer"> ...; // 分支n</span></code><code><span class="code-snippet_outer">} else {</span></code><code><span class="code-snippet_outer"> ...; // 分支n+1</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">if (i == 1) {</span></code><code><span class="code-snippet_outer"> ...; // 分支1</span></code><code><span class="code-snippet_outer">} else if (i == 2) {</span></code><code><span class="code-snippet_outer"> ...; // 分支2</span></code><code><span class="code-snippet_outer">} else if (i == ...) {</span></code><code><span class="code-snippet_outer"> ...; // 分支n</span></code><code><span class="code-snippet_outer">} else {</span></code><code><span class="code-snippet_outer"> ...; // 分支n+1</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">switch (i) {</span></code><code><span class="code-snippet_outer"> case 1 :</span></code><code><span class="code-snippet_outer"> ... // 分支1</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer"> case 2 :</span></code><code><span class="code-snippet_outer"> ... // 分支2</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer"> case ... :</span></code><code><span class="code-snippet_outer"> ... // 分支n</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer"> default :</span></code><code><span class="code-snippet_outer"> ... // 分支n+1</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">switch (i) {</span></code><code><span class="code-snippet_outer"> case 1 :</span></code><code><span class="code-snippet_outer"> ... // 分支1</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer"> case 2 :</span></code><code><span class="code-snippet_outer"> ... // 分支2</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer"> case ... :</span></code><code><span class="code-snippet_outer"> ... // 分支n</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer"> default :</span></code><code><span class="code-snippet_outer"> ... // 分支n+1</span></code><code><span class="code-snippet_outer"> break;</span></code><code><span class="code-snippet_outer">}</span> 备注:如果业务复杂,可以采用Map实现策略模式。 5.字符串 5.1.尽量不要使用正则表达式匹配 正则表达式匹配效率较低,尽量使用字符串匹配操作。 反例: <span class="code-snippet_outer">String source = "a::1,b::2,c::3,d::4";</span></code><code><span class="code-snippet_outer">String target = source.replaceAll("::", "=");</span></code><code><span class="code-snippet_outer">Stringp[] targets = source.spit("::");</span> 1 <span class="code-snippet_outer">String source = "a::1,b::2,c::3,d::4";</span></code><code><span class="code-snippet_outer">String target = source.replaceAll("::", "=");</span></code><code><span class="code-snippet_outer">Stringp[] targets = source.spit("::");</span> 正例: <span class="code-snippet_outer">String source = "a::1,b::2,c::3,d::4";</span></code><code><span class="code-snippet_outer">String target = source.replace("::", "=");</span></code><code><span class="code-snippet_outer">Stringp[] targets = StringUtils.split(source, "::");</span> 1 <span class="code-snippet_outer">String source = "a::1,b::2,c::3,d::4";</span></code><code><span class="code-snippet_outer">String target = source.replace("::", "=");</span></code><code><span class="code-snippet_outer">Stringp[] targets = StringUtils.split(source, "::");</span> 5.2.尽量使用字符替换字符串 字符串的长度不确定,而字符的长度固定为1,查找和匹配的效率自然提高了。 反例: <span class="code-snippet_outer">String source = "a:1,b:2,c:3,d:4";</span></code><code><span class="code-snippet_outer">int index = source.indexOf(":");</span></code><code><span class="code-snippet_outer">String target = source.replace(":", "=");</span> 1 <span class="code-snippet_outer">String source = "a:1,b:2,c:3,d:4";</span></code><code><span class="code-snippet_outer">int index = source.indexOf(":");</span></code><code><span class="code-snippet_outer">String target = source.replace(":", "=");</span> 正例: <span class="code-snippet_outer">String source = "a:1,b:2,c:3,d:4";</span></code><code><span class="code-snippet_outer">int index = source.indexOf(':');</span></code><code><span class="code-snippet_outer">String target = source.replace(':', '=');</span> 1 <span class="code-snippet_outer">String source = "a:1,b:2,c:3,d:4";</span></code><code><span class="code-snippet_outer">int index = source.indexOf(':');</span></code><code><span class="code-snippet_outer">String target = source.replace(':', '=');</span> 5.3.尽量使用StringBuilder进行字符串拼接 String是final类,内容不可修改,所以每次字符串拼接都会生成一个新对象。StringBuilder在初始化时申请了一块内存,以后的字符串拼接都在这块内存中执行,不会申请新内存和生成新对象。 反例: <span class="code-snippet_outer">String s = "";</span></code><code><span class="code-snippet_outer">for (int i = 0; i < 10; i++) {</span></code><code><span class="code-snippet_outer"> if (i != 0) {</span></code><code><span class="code-snippet_outer"> s += ',';</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> s += i;</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">String s = "";</span></code><code><span class="code-snippet_outer">for (int i = 0; i < 10; i++) {</span></code><code><span class="code-snippet_outer"> if (i != 0) {</span></code><code><span class="code-snippet_outer"> s += ',';</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> s += i;</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">StringBuilder sb = <span class="code-snippet__built_in">new</span> StringBuilder(<span class="code-snippet__number">128</span>);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (<span class="code-snippet__keyword">int</span> i = <span class="code-snippet__number">0</span>; i < <span class="code-snippet__number">10</span>; i++) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (i != <span class="code-snippet__number">0</span>) {</span></code><code><span class="code-snippet_outer"> sb.<span class="code-snippet__built_in">append</span>(<span class="code-snippet__string">','</span>);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> sb.<span class="code-snippet__built_in">append</span>(i);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">StringBuilder sb = <span class="code-snippet__built_in">new</span> StringBuilder(<span class="code-snippet__number">128</span>);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (<span class="code-snippet__keyword">int</span> i = <span class="code-snippet__number">0</span>; i < <span class="code-snippet__number">10</span>; i++) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (i != <span class="code-snippet__number">0</span>) {</span></code><code><span class="code-snippet_outer"> sb.<span class="code-snippet__built_in">append</span>(<span class="code-snippet__string">','</span>);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> sb.<span class="code-snippet__built_in">append</span>(i);</span></code><code><span class="code-snippet_outer">}</span> 5.4.不要使用””+转化字符串 使用””+进行字符串转化,使用方便但是效率低,建议使用String.valueOf. 反例: <span class="code-snippet_outer">int i = 12345;</span></code><code><span class="code-snippet_outer">String s = "" + i;</span> 1 <span class="code-snippet_outer">int i = 12345;</span></code><code><span class="code-snippet_outer">String s = "" + i;</span> 正例: <span class="code-snippet_outer">int i = <span class="code-snippet__number">12345</span>;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__built_in">String</span> s = <span class="code-snippet__built_in">String</span>.valueOf(i);</span> 1 <span class="code-snippet_outer">int i = <span class="code-snippet__number">12345</span>;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__built_in">String</span> s = <span class="code-snippet__built_in">String</span>.valueOf(i);</span> 6.数组 6.1.不要使用循环拷贝数组,尽量使用System.arraycopy拷贝数组 推荐使用System.arraycopy拷贝数组,也可以使用Arrays.copyOf拷贝数组。 反例: <span class="code-snippet_outer">int[] sources = new int[] {1, 2, 3, 4, 5};</span></code><code><span class="code-snippet_outer">int[] targets = new int[sources.length];</span></code><code><span class="code-snippet_outer">for (int i = 0; i < targets.length; i++) {</span></code><code><span class="code-snippet_outer"> targets[i] = sources[i];</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">int[] sources = new int[] {1, 2, 3, 4, 5};</span></code><code><span class="code-snippet_outer">int[] targets = new int[sources.length];</span></code><code><span class="code-snippet_outer">for (int i = 0; i < targets.length; i++) {</span></code><code><span class="code-snippet_outer"> targets[i] = sources[i];</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">int[] sources = new int[] {1, 2, 3, 4, 5};</span></code><code><span class="code-snippet_outer">int[] targets = new int[sources.length];</span></code><code><span class="code-snippet_outer">System.arraycopy(sources, 0, targets, 0, targets.length);</span> 1 <span class="code-snippet_outer">int[] sources = new int[] {1, 2, 3, 4, 5};</span></code><code><span class="code-snippet_outer">int[] targets = new int[sources.length];</span></code><code><span class="code-snippet_outer">System.arraycopy(sources, 0, targets, 0, targets.length);</span> 6.2.集合转化为类型T数组时,尽量传入空数组T[0] 将集合转换为数组有2种形式:toArray(new T[n])和toArray(new T[0])。在旧的Java版本中,建议使用toArray(new T[n]),因为创建数组时所需的反射调用非常慢。在OpenJDK6后,反射调用是内在的,使得性能得以提高,toArray(new T[0])比toArray(new T[n])效率更高。此外,toArray(new T[n])比toArray(new T[0])多获取一次列表大小,如果计算列表大小耗时过长,也会导致toArray(new T[n])效率降低。 反例: <span class="code-snippet_outer">List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, ...);</span></code><code><span class="code-snippet_outer">Integer[] integers = integerList.toArray(new Integer[integerList.size()]);</span> 1 <span class="code-snippet_outer">List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, ...);</span></code><code><span class="code-snippet_outer">Integer[] integers = integerList.toArray(new Integer[integerList.size()]);</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><Integer> integerList = Arrays.asList(<span class="code-snippet__number">1</span>, <span class="code-snippet__number">2</span>, <span class="code-snippet__number">3</span>, <span class="code-snippet__number">4</span>, <span class="code-snippet__number">5</span>, ...);</span></code><code><span class="code-snippet_outer">Integer[] integers = integerList.toArray(<span class="code-snippet__keyword">new</span> Integer[<span class="code-snippet__number">0</span>]); <span class="code-snippet__comment">// 勿用new Integer[]{}</span></span> 1 <span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><Integer> integerList = Arrays.asList(<span class="code-snippet__number">1</span>, <span class="code-snippet__number">2</span>, <span class="code-snippet__number">3</span>, <span class="code-snippet__number">4</span>, <span class="code-snippet__number">5</span>, ...);</span></code><code><span class="code-snippet_outer">Integer[] integers = integerList.toArray(<span class="code-snippet__keyword">new</span> Integer[<span class="code-snippet__number">0</span>]); <span class="code-snippet__comment">// 勿用new Integer[]{}</span></span> 建议:集合应该提供一个toArray(Class<T> clazz)方法,避免无用的空数组初始化(new T[0])。 6.3.集合转化为Object数组时,尽量使用toArray()方法 转化Object数组时,没有必要使用toArray[new Object[0]],可以直接使用toArray()。避免了类型的判断,也避免了空数组的申请,所以效率会更高。 反例: <span class="code-snippet_outer">List<Object> objectList = Arrays.asList(1, "2", 3, "4", 5, ...);</span></code><code><span class="code-snippet_outer">Object[] objects = objectList.toArray(new Object[0]);</span> 1 <span class="code-snippet_outer">List<Object> objectList = Arrays.asList(1, "2", 3, "4", 5, ...);</span></code><code><span class="code-snippet_outer">Object[] objects = objectList.toArray(new Object[0]);</span> 正例: <span class="code-snippet_outer">List<<span class="code-snippet__built_in">Object</span>> objectList = Arrays.asList(<span class="code-snippet__number">1</span>, <span class="code-snippet__string">"2"</span>, <span class="code-snippet__number">3</span>, <span class="code-snippet__string">"4"</span>, <span class="code-snippet__number">5</span>, ...);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__built_in">Object</span>[] objects = objectList.toArray();</span> 1 <span class="code-snippet_outer">List<<span class="code-snippet__built_in">Object</span>> objectList = Arrays.asList(<span class="code-snippet__number">1</span>, <span class="code-snippet__string">"2"</span>, <span class="code-snippet__number">3</span>, <span class="code-snippet__string">"4"</span>, <span class="code-snippet__number">5</span>, ...);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__built_in">Object</span>[] objects = objectList.toArray();</span> 7.集合 7.1.初始化集合时,尽量指定集合大小 Java集合初始化时都会指定一个默认大小,当默认大小不再满足数据需求时就会扩容,每次扩容的时间复杂度有可能是O(n)。所以,尽量指定预知的集合大小,就能避免或减少集合的扩容次数。 反例: <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">Set<Long> userSet = new HashSet<>();</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = new HashMap<>();</span></code><code><span class="code-snippet_outer">List<UserVO> userList = new ArrayList<>();</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> userSet.add(userDO.getId());</span></code><code><span class="code-snippet_outer"> userMap.put(userDO.getId(), userDO);</span></code><code><span class="code-snippet_outer"> userList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">Set<Long> userSet = new HashSet<>();</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = new HashMap<>();</span></code><code><span class="code-snippet_outer">List<UserVO> userList = new ArrayList<>();</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> userSet.add(userDO.getId());</span></code><code><span class="code-snippet_outer"> userMap.put(userDO.getId(), userDO);</span></code><code><span class="code-snippet_outer"> userList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">int userSize = userDOList.size();</span></code><code><span class="code-snippet_outer">Set<Long> userSet = new HashSet<>(userSize);</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = new HashMap<>((int) Math.ceil(userSize * 4.0 / 3));</span></code><code><span class="code-snippet_outer">List<UserVO> userList = new ArrayList<>(userSize);</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> userSet.add(userDO.getId());</span></code><code><span class="code-snippet_outer"> userMap.put(userDO.getId(), userDO);</span></code><code><span class="code-snippet_outer"> userList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">int userSize = userDOList.size();</span></code><code><span class="code-snippet_outer">Set<Long> userSet = new HashSet<>(userSize);</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = new HashMap<>((int) Math.ceil(userSize * 4.0 / 3));</span></code><code><span class="code-snippet_outer">List<UserVO> userList = new ArrayList<>(userSize);</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> userSet.add(userDO.getId());</span></code><code><span class="code-snippet_outer"> userMap.put(userDO.getId(), userDO);</span></code><code><span class="code-snippet_outer"> userList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer">}</span> 7.2.不要使用循环拷贝集合,尽量使用JDK提供的方法拷贝集合 JDK提供的方法可以一步指定集合的容量,避免多次扩容浪费时间和空间。同时,这些方法的底层也是调用System.arraycopy方法实现,进行数据的批量拷贝效率更高。 反例: <span class="code-snippet_outer">List<UserDO> user1List = ...;</span></code><code><span class="code-snippet_outer">List<UserDO> user2List = ...;</span></code><code><span class="code-snippet_outer">List<UserDO> userList = new ArrayList<>(user1List.size() + user2List.size());</span></code><code><span class="code-snippet_outer">for (UserDO user1 : user1List) {</span></code><code><span class="code-snippet_outer"> userList.add(user1);</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">for (UserDO user2 : user2List) {</span></code><code><span class="code-snippet_outer"> userList.add(user2);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> user1List = ...;</span></code><code><span class="code-snippet_outer">List<UserDO> user2List = ...;</span></code><code><span class="code-snippet_outer">List<UserDO> userList = new ArrayList<>(user1List.size() + user2List.size());</span></code><code><span class="code-snippet_outer">for (UserDO user1 : user1List) {</span></code><code><span class="code-snippet_outer"> userList.add(user1);</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">for (UserDO user2 : user2List) {</span></code><code><span class="code-snippet_outer"> userList.add(user2);</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<span class="code-snippet__tag"><<span class="code-snippet__name">UserDO</span>></span> user1List = ...;</span></code><code><span class="code-snippet_outer">List<span class="code-snippet__tag"><<span class="code-snippet__name">UserDO</span>></span> user2List = ...;</span></code><code><span class="code-snippet_outer">List<span class="code-snippet__tag"><<span class="code-snippet__name">UserDO</span>></span> userList = new ArrayList<span class="code-snippet__tag"><></span>(user1List.size() + user2List.size());</span></code><code><span class="code-snippet_outer">userList.addAll(user1List);</span></code><code><span class="code-snippet_outer">userList.addAll(user2List);</span> 1 <span class="code-snippet_outer">List<span class="code-snippet__tag"><<span class="code-snippet__name">UserDO</span>></span> user1List = ...;</span></code><code><span class="code-snippet_outer">List<span class="code-snippet__tag"><<span class="code-snippet__name">UserDO</span>></span> user2List = ...;</span></code><code><span class="code-snippet_outer">List<span class="code-snippet__tag"><<span class="code-snippet__name">UserDO</span>></span> userList = new ArrayList<span class="code-snippet__tag"><></span>(user1List.size() + user2List.size());</span></code><code><span class="code-snippet_outer">userList.addAll(user1List);</span></code><code><span class="code-snippet_outer">userList.addAll(user2List);</span> 7.3.尽量使用Arrays.asList转化数组为列表 原理与”不要使用循环拷贝集合,尽量使用JDK提供的方法拷贝集合”类似。 反例: <span class="code-snippet_outer">List<String> typeList = new ArrayList<>(8);</span></code><code><span class="code-snippet_outer">typeList.add("Short");</span></code><code><span class="code-snippet_outer">typeList.add("Integer");</span></code><code><span class="code-snippet_outer">typeList.add("Long");</span></code><code> </code><code><span class="code-snippet_outer">String[] names = ...;</span></code><code><span class="code-snippet_outer">List<String> nameList = ...;</span></code><code><span class="code-snippet_outer">for (String name : names) {</span></code><code><span class="code-snippet_outer"> nameList.add(name);</span></code><code><span class="code-snippet_outer">}</span> 12 <span class="code-snippet_outer">List<String> typeList = new ArrayList<>(8);</span></code><code><span class="code-snippet_outer">typeList.add("Short");</span></code><code><span class="code-snippet_outer">typeList.add("Integer");</span></code><code><span class="code-snippet_outer">typeList.add("Long");</span></code><code></code><code><span class="code-snippet_outer">String[] names = ...;</span></code><code><span class="code-snippet_outer">List<String> nameList = ...;</span></code><code><span class="code-snippet_outer">for (String name : names) {</span></code><code><span class="code-snippet_outer"> nameList.add(name);</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<<span class="code-snippet__built_in">String</span>> typeList = Arrays.asList(<span class="code-snippet__string">"Short"</span>, <span class="code-snippet__string">"Integer"</span>, <span class="code-snippet__string">"Long"</span>);</span></code><code> </code><code><span class="code-snippet_outer"><span class="code-snippet__built_in">String</span>[] names = ...;</span></code><code><span class="code-snippet_outer">List<<span class="code-snippet__built_in">String</span>> nameList = ...;</span></code><code><span class="code-snippet_outer">nameList.addAll(Arrays.asList(names));</span> 12 <span class="code-snippet_outer">List<<span class="code-snippet__built_in">String</span>> typeList = Arrays.asList(<span class="code-snippet__string">"Short"</span>, <span class="code-snippet__string">"Integer"</span>, <span class="code-snippet__string">"Long"</span>);</span></code><code></code><code><span class="code-snippet_outer"><span class="code-snippet__built_in">String</span>[] names = ...;</span></code><code><span class="code-snippet_outer">List<<span class="code-snippet__built_in">String</span>> nameList = ...;</span></code><code><span class="code-snippet_outer">nameList.addAll(Arrays.asList(names));</span> 7.4.直接迭代需要使用的集合 直接迭代需要使用的集合,无需通过其它操作获取数据。 反例: <span class="code-snippet_outer">Map<Long, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer">for (Long userId : userMap.keySet()) {</span></code><code><span class="code-snippet_outer"> UserDO user = userMap.get(userId);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">Map<Long, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer">for (Long userId : userMap.keySet()) {</span></code><code><span class="code-snippet_outer"> UserDO user = userMap.get(userId);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">Map<<span class="code-snippet__built_in">Long</span>, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (Map.Entry<<span class="code-snippet__built_in">Long</span>, UserDO> userEntry : userMap.entrySet()) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__built_in">Long</span> userId = userEntry.getKey();</span></code><code><span class="code-snippet_outer"> UserDO user = userEntry.getValue();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">Map<<span class="code-snippet__built_in">Long</span>, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (Map.Entry<<span class="code-snippet__built_in">Long</span>, UserDO> userEntry : userMap.entrySet()) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__built_in">Long</span> userId = userEntry.getKey();</span></code><code><span class="code-snippet_outer"> UserDO user = userEntry.getValue();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 7.5.不要使用size方法检测空,必须使用isEmpty方法检测空 使用size方法来检测空逻辑上没有问题,但使用isEmpty方法使得代码更易读,并且可以获得更好的性能。任何isEmpty方法实现的时间复杂度都是O(1),但是某些size方法实现的时间复杂度有可能是O(n)。 反例: <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">if (userList.size() == 0) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer">if (userMap.size() == 0) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">if (userList.size() == 0) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer">if (userMap.size() == 0) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">if (userList.isEmpty()) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer">if (userMap.isEmpty()) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<UserDO> userList = ...;</span></code><code><span class="code-snippet_outer">if (userList.isEmpty()) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">Map<Long, UserDO> userMap = ...;</span></code><code><span class="code-snippet_outer">if (userMap.isEmpty()) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 7.6.非随机访问的List,尽量使用迭代代替随机访问 对于列表,可分为随机访问和非随机访问两类,可以用是否实现RandomAccess接口判断。随机访问列表,直接通过get获取数据不影响效率。而非随机访问列表,通过get获取数据效率极低。 反例: <span class="code-snippet_outer">LinkedList<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">int size = userDOList.size();</span></code><code><span class="code-snippet_outer">for (int i = 0; i < size; i++) {</span></code><code><span class="code-snippet_outer"> UserDO userDO = userDOList.get(i);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">LinkedList<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">int size = userDOList.size();</span></code><code><span class="code-snippet_outer">for (int i = 0; i < size; i++) {</span></code><code><span class="code-snippet_outer"> UserDO userDO = userDOList.get(i);</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">LinkedList<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">LinkedList<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 其实,不管列表支不支持随机访问,都应该使用迭代进行遍历。 7.7.尽量使用HashSet判断值存在 在Java集合类库中,List的contains方法普遍时间复杂度是O(n),而HashSet的时间复杂度为O(1)。如果需要频繁调用contains方法查找数据,可以先将List转换成HashSet。 反例: <span class="code-snippet_outer">List<Long> adminIdList = ...;</span></code><code><span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> if (adminIdList.contains(userDO.getId())) {</span></code><code><span class="code-snippet_outer"> userVOList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">List<Long> adminIdList = ...;</span></code><code><span class="code-snippet_outer">List<UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer">List<UserVO> userVOList = new ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer">for (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> if (adminIdList.contains(userDO.getId())) {</span></code><code><span class="code-snippet_outer"> userVOList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">Set<Long> adminIdSet = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><UserVO> userVOList = <span class="code-snippet__keyword">new</span> ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (adminIdSet.contains(userDO.getId())) {</span></code><code><span class="code-snippet_outer"> userVOList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">Set<Long> adminIdSet = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><UserDO> userDOList = ...;</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">List</span><UserVO> userVOList = <span class="code-snippet__keyword">new</span> ArrayList<>(userDOList.size());</span></code><code><span class="code-snippet_outer"><span class="code-snippet__keyword">for</span> (UserDO userDO : userDOList) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (adminIdSet.contains(userDO.getId())) {</span></code><code><span class="code-snippet_outer"> userVOList.add(transUser(userDO));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 7.8.避免先判断存在再进行获取 如果需要先判断存在再进行获取,可以直接获取并判断空,从而避免了二次查找操作。 反例: <span class="code-snippet_outer">public static UserVO transUser(UserDO user, Map<Long, RoleDO> roleMap) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(user.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> if (roleMap.contains(user.getRoleId())) {</span></code><code><span class="code-snippet_outer"> RoleDO role = roleMap.get(user.getRoleId());</span></code><code><span class="code-snippet_outer"> userVO.setRole(transRole(role));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public static UserVO transUser(UserDO user, Map<Long, RoleDO> roleMap) {</span></code><code><span class="code-snippet_outer"> UserVO userVO = new UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(user.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> if (roleMap.contains(user.getRoleId())) {</span></code><code><span class="code-snippet_outer"> RoleDO role = roleMap.get(user.getRoleId());</span></code><code><span class="code-snippet_outer"> userVO.setRole(transRole(role));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">static</span> UserVO <span class="code-snippet__title">transUser</span>(<span class="code-snippet__params">UserDO user, Map<Long, RoleDO> roleMap</span>)</span> {</span></code><code><span class="code-snippet_outer"> UserVO userVO = <span class="code-snippet__keyword">new</span> UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(user.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> RoleDO role = roleMap.<span class="code-snippet__keyword">get</span>(user.getRoleId());</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (Objects.nonNull(role)) {</span></code><code><span class="code-snippet_outer"> userVO.setRole(transRole(role));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">static</span> UserVO <span class="code-snippet__title">transUser</span>(<span class="code-snippet__params">UserDO user, Map<Long, RoleDO> roleMap</span>)</span> {</span></code><code><span class="code-snippet_outer"> UserVO userVO = <span class="code-snippet__keyword">new</span> UserVO();</span></code><code><span class="code-snippet_outer"> userVO.setId(user.getId());</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer"> RoleDO role = roleMap.<span class="code-snippet__keyword">get</span>(user.getRoleId());</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (Objects.nonNull(role)) {</span></code><code><span class="code-snippet_outer"> userVO.setRole(transRole(role));</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 8.异常 8.1.直接捕获对应的异常 直接捕获对应的异常,避免用instanceof判断,效率更高代码更简洁。 反例: <span class="code-snippet_outer">try {</span></code><code><span class="code-snippet_outer"> saveData();</span></code><code><span class="code-snippet_outer">} catch (Exception e) {</span></code><code><span class="code-snippet_outer"> if (e instanceof IOException) {</span></code><code><span class="code-snippet_outer"> log.error("保存数据IO异常", e);</span></code><code><span class="code-snippet_outer"> } else {</span></code><code><span class="code-snippet_outer"> log.error("保存数据其它异常", e);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">try {</span></code><code><span class="code-snippet_outer"> saveData();</span></code><code><span class="code-snippet_outer">} catch (Exception e) {</span></code><code><span class="code-snippet_outer"> if (e instanceof IOException) {</span></code><code><span class="code-snippet_outer"> log.error("保存数据IO异常", e);</span></code><code><span class="code-snippet_outer"> } else {</span></code><code><span class="code-snippet_outer"> log.error("保存数据其它异常", e);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">try {</span></code><code><span class="code-snippet_outer"> saveData();</span></code><code><span class="code-snippet_outer">} catch (IOException e) {</span></code><code><span class="code-snippet_outer"> log.error("保存数据IO异常", e);</span></code><code><span class="code-snippet_outer">} catch (Exception e) {</span></code><code><span class="code-snippet_outer"> log.error("保存数据其它异常", e);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">try {</span></code><code><span class="code-snippet_outer"> saveData();</span></code><code><span class="code-snippet_outer">} catch (IOException e) {</span></code><code><span class="code-snippet_outer"> log.error("保存数据IO异常", e);</span></code><code><span class="code-snippet_outer">} catch (Exception e) {</span></code><code><span class="code-snippet_outer"> log.error("保存数据其它异常", e);</span></code><code><span class="code-snippet_outer">}</span> 8.2.尽量避免在循环中捕获异常 当循环体抛出异常后,无需循环继续执行时,没有必要在循环体中捕获异常。因为,过多的捕获异常会降低程序执行效率。 反例: <span class="code-snippet_outer">public Double sum(List<String> valueList) {</span></code><code><span class="code-snippet_outer"> double sum = 0.0D;</span></code><code><span class="code-snippet_outer"> for (String value : valueList) {</span></code><code><span class="code-snippet_outer"> try {</span></code><code><span class="code-snippet_outer"> sum += Double.parseDouble(value);</span></code><code><span class="code-snippet_outer"> } catch (NumberFormatException e) {</span></code><code><span class="code-snippet_outer"> return null;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return sum;</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">public Double sum(List<String> valueList) {</span></code><code><span class="code-snippet_outer"> double sum = 0.0D;</span></code><code><span class="code-snippet_outer"> for (String value : valueList) {</span></code><code><span class="code-snippet_outer"> try {</span></code><code><span class="code-snippet_outer"> sum += Double.parseDouble(value);</span></code><code><span class="code-snippet_outer"> } catch (NumberFormatException e) {</span></code><code><span class="code-snippet_outer"> return null;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> return sum;</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> Double <span class="code-snippet__title">sum</span>(<span class="code-snippet__params">List<String> valueList</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">double</span> sum = <span class="code-snippet__number">0.0</span>D;</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">try</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">for</span> (String <span class="code-snippet__keyword">value</span> : valueList) {</span></code><code><span class="code-snippet_outer"> sum += Double.parseDouble(<span class="code-snippet__keyword">value</span>);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> } <span class="code-snippet__keyword">catch</span> (NumberFormatException e) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> <span class="code-snippet__literal">null</span>;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> sum;</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> Double <span class="code-snippet__title">sum</span>(<span class="code-snippet__params">List<String> valueList</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">double</span> sum = <span class="code-snippet__number">0.0</span>D;</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">try</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">for</span> (String <span class="code-snippet__keyword">value</span> : valueList) {</span></code><code><span class="code-snippet_outer"> sum += Double.parseDouble(<span class="code-snippet__keyword">value</span>);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> } <span class="code-snippet__keyword">catch</span> (NumberFormatException e) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> <span class="code-snippet__literal">null</span>;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> sum;</span></code><code><span class="code-snippet_outer">}</span> 8.3.禁止使用异常控制业务流程 相对于条件表达式,异常的处理效率更低。 反例: <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">static</span> boolean <span class="code-snippet__title">isValid</span>(<span class="code-snippet__params">UserDO user</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">try</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> Boolean.TRUE.<span class="code-snippet__keyword">equals</span>(user.getIsValid());</span></code><code><span class="code-snippet_outer"> } <span class="code-snippet__keyword">catch</span>(NullPointerException e) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> <span class="code-snippet__literal">false</span>;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">static</span> boolean <span class="code-snippet__title">isValid</span>(<span class="code-snippet__params">UserDO user</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">try</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> Boolean.TRUE.<span class="code-snippet__keyword">equals</span>(user.getIsValid());</span></code><code><span class="code-snippet_outer"> } <span class="code-snippet__keyword">catch</span>(NullPointerException e) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> <span class="code-snippet__literal">false</span>;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">static</span> boolean <span class="code-snippet__title">isValid</span>(<span class="code-snippet__params">UserDO user</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> <span class="code-snippet__literal">false</span>;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> Boolean.TRUE.<span class="code-snippet__keyword">equals</span>(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">static</span> boolean <span class="code-snippet__title">isValid</span>(<span class="code-snippet__params">UserDO user</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">if</span> (Objects.isNull(user)) {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> <span class="code-snippet__literal">false</span>;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">return</span> Boolean.TRUE.<span class="code-snippet__keyword">equals</span>(user.getIsValid());</span></code><code><span class="code-snippet_outer">}</span> 9.缓冲区 9.1.初始化时尽量指定缓冲区大小 初始化时,指定缓冲区的预期容量大小,避免多次扩容浪费时间和空间。 反例: <span class="code-snippet_outer">StringBuffer buffer = <span class="code-snippet__keyword">new</span> StringBuffer();</span></code><code><span class="code-snippet_outer">StringBuilder builder = <span class="code-snippet__keyword">new</span> StringBuilder();</span> 1 <span class="code-snippet_outer">StringBuffer buffer = <span class="code-snippet__keyword">new</span> StringBuffer();</span></code><code><span class="code-snippet_outer">StringBuilder builder = <span class="code-snippet__keyword">new</span> StringBuilder();</span> 正例: <span class="code-snippet_outer">StringBuffer buffer = <span class="code-snippet__keyword">new</span> StringBuffer(<span class="code-snippet__number">1024</span>);</span></code><code><span class="code-snippet_outer">StringBuilder builder = <span class="code-snippet__keyword">new</span> StringBuilder(<span class="code-snippet__number">1024</span>);</span> 1 <span class="code-snippet_outer">StringBuffer buffer = <span class="code-snippet__keyword">new</span> StringBuffer(<span class="code-snippet__number">1024</span>);</span></code><code><span class="code-snippet_outer">StringBuilder builder = <span class="code-snippet__keyword">new</span> StringBuilder(<span class="code-snippet__number">1024</span>);</span> 9.2.尽量重复使用同一缓冲区 针对缓冲区,Java虚拟机需要花时间生成对象,还要花时间进行垃圾回收处理。所以,尽量重复利用缓冲区。 反例: <span class="code-snippet_outer">StringBuilder builder1 = new StringBuilder(128);</span></code><code><span class="code-snippet_outer">builder1.append("update t_user set name = '").append(userName).append("' where id = ").append(userId);</span></code><code><span class="code-snippet_outer">statement.executeUpdate(builder1.toString());</span></code><code><span class="code-snippet_outer">StringBuilder builder2 = new StringBuilder(128);</span></code><code><span class="code-snippet_outer">builder2.append("select id, name from t_user where id = ").append(userId);</span></code><code><span class="code-snippet_outer">ResultSet resultSet = statement.executeQuery(builder2.toString());</span></code><code><span class="code-snippet_outer">...</span> 1 <span class="code-snippet_outer">StringBuilder builder1 = new StringBuilder(128);</span></code><code><span class="code-snippet_outer">builder1.append("update t_user set name = '").append(userName).append("' where id = ").append(userId);</span></code><code><span class="code-snippet_outer">statement.executeUpdate(builder1.toString());</span></code><code><span class="code-snippet_outer">StringBuilder builder2 = new StringBuilder(128);</span></code><code><span class="code-snippet_outer">builder2.append("select id, name from t_user where id = ").append(userId);</span></code><code><span class="code-snippet_outer">ResultSet resultSet = statement.executeQuery(builder2.toString());</span></code><code><span class="code-snippet_outer">...</span> 正例: <span class="code-snippet_outer">StringBuilder builder = new StringBuilder(128);</span></code><code><span class="code-snippet_outer">builder.append("<span class="code-snippet__keyword">update</span> t_user <span class="code-snippet__keyword">set</span> <span class="code-snippet__keyword">name</span> = <span class="code-snippet__string">'").append(userName).append("'</span> <span class="code-snippet__keyword">where</span> <span class="code-snippet__keyword">id</span> = <span class="code-snippet__string">").append(userId);</span></span></code><code><span class="code-snippet_outer">statement.executeUpdate(builder.toString());</span></code><code><span class="code-snippet_outer">builder.setLength(0);</span></code><code><span class="code-snippet_outer">builder.append("<span class="code-snippet__keyword">select</span> <span class="code-snippet__keyword">id</span>, <span class="code-snippet__keyword">name</span> <span class="code-snippet__keyword">from</span> t_user <span class="code-snippet__keyword">where</span> <span class="code-snippet__keyword">id</span> = <span class="code-snippet__string">").append(userId);</span></span></code><code><span class="code-snippet_outer">ResultSet resultSet = statement.executeQuery(builder.toString());</span></code><code><span class="code-snippet_outer">...</span> 1 <span class="code-snippet_outer">StringBuilder builder = new StringBuilder(128);</span></code><code><span class="code-snippet_outer">builder.append("<span class="code-snippet__keyword">update</span> t_user <span class="code-snippet__keyword">set</span> <span class="code-snippet__keyword">name</span> = <span class="code-snippet__string">'").append(userName).append("'</span> <span class="code-snippet__keyword">where</span> <span class="code-snippet__keyword">id</span> = <span class="code-snippet__string">").append(userId);</span></span></code><code><span class="code-snippet_outer">statement.executeUpdate(builder.toString());</span></code><code><span class="code-snippet_outer">builder.setLength(0);</span></code><code><span class="code-snippet_outer">builder.append("<span class="code-snippet__keyword">select</span> <span class="code-snippet__keyword">id</span>, <span class="code-snippet__keyword">name</span> <span class="code-snippet__keyword">from</span> t_user <span class="code-snippet__keyword">where</span> <span class="code-snippet__keyword">id</span> = <span class="code-snippet__string">").append(userId);</span></span></code><code><span class="code-snippet_outer">ResultSet resultSet = statement.executeQuery(builder.toString());</span></code><code><span class="code-snippet_outer">...</span> 其中,使用setLength方法让缓冲区重新从0开始。 9.3.尽量设计使用同一缓冲区 为了提高程序运行效率,在设计上尽量使用同一缓冲区。 反例: <span class="code-snippet_outer">// 转化XML(UserDO)</span></code><code><span class="code-snippet_outer">public static String toXml(UserDO user) {</span></code><code><span class="code-snippet_outer"> StringBuilder builder = new StringBuilder(128);</span></code><code><span class="code-snippet_outer"> builder.append("<UserDO>");</span></code><code><span class="code-snippet_outer"> builder.append(toXml(user.getId()));</span></code><code><span class="code-snippet_outer"> builder.append(toXml(user.getName()));</span></code><code><span class="code-snippet_outer"> builder.append(toXml(user.getRole()));</span></code><code><span class="code-snippet_outer"> builder.append("</UserDO>");</span></code><code><span class="code-snippet_outer"> return builder.toString();</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">// 转化XML(Long)</span></code><code><span class="code-snippet_outer">public static String toXml(Long value) {</span></code><code><span class="code-snippet_outer"> StringBuilder builder = new StringBuilder(128);</span></code><code><span class="code-snippet_outer"> builder.append("<Long>");</span></code><code><span class="code-snippet_outer"> builder.append(value);</span></code><code><span class="code-snippet_outer"> builder.append("</Long>");</span></code><code><span class="code-snippet_outer"> return builder.toString();</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">...</span></code><code> </code><code><span class="code-snippet_outer">// 使用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">String xml = toXml(user);</span> 12 <span class="code-snippet_outer">// 转化XML(UserDO)</span></code><code><span class="code-snippet_outer">public static String toXml(UserDO user) {</span></code><code><span class="code-snippet_outer"> StringBuilder builder = new StringBuilder(128);</span></code><code><span class="code-snippet_outer"> builder.append("<UserDO>");</span></code><code><span class="code-snippet_outer"> builder.append(toXml(user.getId()));</span></code><code><span class="code-snippet_outer"> builder.append(toXml(user.getName()));</span></code><code><span class="code-snippet_outer"> builder.append(toXml(user.getRole()));</span></code><code><span class="code-snippet_outer"> builder.append("</UserDO>");</span></code><code><span class="code-snippet_outer"> return builder.toString();</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">// 转化XML(Long)</span></code><code><span class="code-snippet_outer">public static String toXml(Long value) {</span></code><code><span class="code-snippet_outer"> StringBuilder builder = new StringBuilder(128);</span></code><code><span class="code-snippet_outer"> builder.append("<Long>");</span></code><code><span class="code-snippet_outer"> builder.append(value);</span></code><code><span class="code-snippet_outer"> builder.append("</Long>");</span></code><code><span class="code-snippet_outer"> return builder.toString();</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">...</span></code><code></code><code><span class="code-snippet_outer">// 使用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">String xml = toXml(user);</span> 正例: <span class="code-snippet_outer">// 转化XML(UserDO)</span></code><code><span class="code-snippet_outer">public static void toXml(StringBuilder builder, UserDO user) {</span></code><code><span class="code-snippet_outer"> builder.append("<UserDO>");</span></code><code><span class="code-snippet_outer"> toXml(builder, user.getId());</span></code><code><span class="code-snippet_outer"> toXml(builder, user.getName());</span></code><code><span class="code-snippet_outer"> toXml(builder, user.getRole());</span></code><code><span class="code-snippet_outer"> builder.append("</UserDO>");</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">// 转化XML(Long)</span></code><code><span class="code-snippet_outer">public static void toXml(StringBuilder builder, Long value) {</span></code><code><span class="code-snippet_outer"> builder.append("<Long>");</span></code><code><span class="code-snippet_outer"> builder.append(value);</span></code><code><span class="code-snippet_outer"> builder.append("</Long>");</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">...</span></code><code> </code><code><span class="code-snippet_outer">// 使用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">StringBuilder builder = new StringBuilder(1024);</span></code><code><span class="code-snippet_outer">toXml(builder, user);</span></code><code><span class="code-snippet_outer">String xml = builder.toString();</span> 12 <span class="code-snippet_outer">// 转化XML(UserDO)</span></code><code><span class="code-snippet_outer">public static void toXml(StringBuilder builder, UserDO user) {</span></code><code><span class="code-snippet_outer"> builder.append("<UserDO>");</span></code><code><span class="code-snippet_outer"> toXml(builder, user.getId());</span></code><code><span class="code-snippet_outer"> toXml(builder, user.getName());</span></code><code><span class="code-snippet_outer"> toXml(builder, user.getRole());</span></code><code><span class="code-snippet_outer"> builder.append("</UserDO>");</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">// 转化XML(Long)</span></code><code><span class="code-snippet_outer">public static void toXml(StringBuilder builder, Long value) {</span></code><code><span class="code-snippet_outer"> builder.append("<Long>");</span></code><code><span class="code-snippet_outer"> builder.append(value);</span></code><code><span class="code-snippet_outer"> builder.append("</Long>");</span></code><code><span class="code-snippet_outer">}</span></code><code><span class="code-snippet_outer">...</span></code><code></code><code><span class="code-snippet_outer">// 使用代码</span></code><code><span class="code-snippet_outer">UserDO user = ...;</span></code><code><span class="code-snippet_outer">StringBuilder builder = new StringBuilder(1024);</span></code><code><span class="code-snippet_outer">toXml(builder, user);</span></code><code><span class="code-snippet_outer">String xml = builder.toString();</span> 去掉每个转化方法中的缓冲区申请,申请一个缓冲区给每个转化方法使用。从时间上来说,节约了大量缓冲区的申请释放时间;从空间上来说,节约了大量缓冲区的临时存储空间。 9.4.尽量使用缓冲流减少IO操作 使用缓冲流BufferedReader、BufferedWriter、BufferedInputStream、BufferedOutputStream等,可以大幅较少IO次数并提升IO速度。 反例: <span class="code-snippet_outer">try (FileInputStream input = new FileInputStream("a");</span></code><code><span class="code-snippet_outer"> FileOutputStream output = new FileOutputStream("b")) {</span></code><code><span class="code-snippet_outer"> int size = 0;</span></code><code><span class="code-snippet_outer"> byte[] temp = new byte[1024];</span></code><code><span class="code-snippet_outer"> while ((size = input.read(temp)) != -1) {</span></code><code><span class="code-snippet_outer"> output.write(temp, 0, size);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">} catch (IOException e) {</span></code><code><span class="code-snippet_outer"> log.error("复制文件异常", e);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">try (FileInputStream input = new FileInputStream("a");</span></code><code><span class="code-snippet_outer"> FileOutputStream output = new FileOutputStream("b")) {</span></code><code><span class="code-snippet_outer"> int size = 0;</span></code><code><span class="code-snippet_outer"> byte[] temp = new byte[1024];</span></code><code><span class="code-snippet_outer"> while ((size = input.read(temp)) != -1) {</span></code><code><span class="code-snippet_outer"> output.write(temp, 0, size);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">} catch (IOException e) {</span></code><code><span class="code-snippet_outer"> log.error("复制文件异常", e);</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">try (BufferedInputStream input = new BufferedInputStream(new FileInputStream("a"));</span></code><code><span class="code-snippet_outer"> BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("b"))) {</span></code><code><span class="code-snippet_outer"> int size = 0;</span></code><code><span class="code-snippet_outer"> byte[] temp = new byte[1024];</span></code><code><span class="code-snippet_outer"> while ((size = input.read(temp)) != -1) {</span></code><code><span class="code-snippet_outer"> output.write(temp, 0, size);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">} catch (IOException e) {</span></code><code><span class="code-snippet_outer"> log.error("复制文件异常", e);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">try (BufferedInputStream input = new BufferedInputStream(new FileInputStream("a"));</span></code><code><span class="code-snippet_outer"> BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("b"))) {</span></code><code><span class="code-snippet_outer"> int size = 0;</span></code><code><span class="code-snippet_outer"> byte[] temp = new byte[1024];</span></code><code><span class="code-snippet_outer"> while ((size = input.read(temp)) != -1) {</span></code><code><span class="code-snippet_outer"> output.write(temp, 0, size);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">} catch (IOException e) {</span></code><code><span class="code-snippet_outer"> log.error("复制文件异常", e);</span></code><code><span class="code-snippet_outer">}</span> 其中,可以根据实际情况手动指定缓冲流的大小,把缓冲流的缓冲作用发挥到最大。 10.线程 10.1.在单线程中,尽量使用非线程安全类 使用非线程安全类,避免了不必要的同步开销。 反例: <span class="code-snippet_outer">StringBuffer buffer = new StringBuffer(128);</span></code><code><span class="code-snippet_outer">buffer.append("select * from ").append(T_USER).append(" where id = ?");</span> 1 <span class="code-snippet_outer">StringBuffer buffer = new StringBuffer(128);</span></code><code><span class="code-snippet_outer">buffer.append("select * from ").append(T_USER).append(" where id = ?");</span> 正例: <span class="code-snippet_outer">StringBuilder buffer = <span class="code-snippet__built_in">new</span> StringBuilder(<span class="code-snippet__number">128</span>);</span></code><code><span class="code-snippet_outer">buffer.<span class="code-snippet__built_in">append</span>(<span class="code-snippet__string">"select * from "</span>).<span class="code-snippet__built_in">append</span>(T_USER).<span class="code-snippet__built_in">append</span>(<span class="code-snippet__string">" where id = ?"</span>);</span> 1 <span class="code-snippet_outer">StringBuilder buffer = <span class="code-snippet__built_in">new</span> StringBuilder(<span class="code-snippet__number">128</span>);</span></code><code><span class="code-snippet_outer">buffer.<span class="code-snippet__built_in">append</span>(<span class="code-snippet__string">"select * from "</span>).<span class="code-snippet__built_in">append</span>(T_USER).<span class="code-snippet__built_in">append</span>(<span class="code-snippet__string">" where id = ?"</span>);</span> 10.2.在多线程中,尽量使用线程安全类 使用线程安全类,比自己实现的同步代码更简洁更高效。 反例: <span class="code-snippet_outer">private volatile int counter = 0;</span></code><code><span class="code-snippet_outer">public void access(Long userId) {</span></code><code><span class="code-snippet_outer"> synchronized (this) {</span></code><code><span class="code-snippet_outer"> counter++;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">private volatile int counter = 0;</span></code><code><span class="code-snippet_outer">public void access(Long userId) {</span></code><code><span class="code-snippet_outer"> synchronized (this) {</span></code><code><span class="code-snippet_outer"> counter++;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__keyword">private</span> <span class="code-snippet__keyword">final</span> AtomicInteger counter = <span class="code-snippet__keyword">new</span> AtomicInteger(<span class="code-snippet__number">0</span>);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">void</span> <span class="code-snippet__title">access</span><span class="code-snippet__params">(Long userId)</span> </span>{</span></code><code><span class="code-snippet_outer"> counter.incrementAndGet();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__keyword">private</span> <span class="code-snippet__keyword">final</span> AtomicInteger counter = <span class="code-snippet__keyword">new</span> AtomicInteger(<span class="code-snippet__number">0</span>);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">void</span> <span class="code-snippet__title">access</span><span class="code-snippet__params">(Long userId)</span> </span>{</span></code><code><span class="code-snippet_outer"> counter.incrementAndGet();</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span> 10.3.尽量减少同步代码块范围 在一个方法中,可能只有一小部分的逻辑是需要同步控制的,如果同步控制了整个方法会影响执行效率。所以,尽量减少同步代码块的范围,只对需要进行同步的代码进行同步。 反例: <span class="code-snippet_outer">private volatile int counter = 0;</span></code><code><span class="code-snippet_outer">public synchronized void access(Long userId) {</span></code><code><span class="code-snippet_outer"> counter++;</span></code><code><span class="code-snippet_outer"> ... // 非同步操作</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">private volatile int counter = 0;</span></code><code><span class="code-snippet_outer">public synchronized void access(Long userId) {</span></code><code><span class="code-snippet_outer"> counter++;</span></code><code><span class="code-snippet_outer"> ... // 非同步操作</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">private volatile int counter = 0;</span></code><code><span class="code-snippet_outer">public void access(Long userId) {</span></code><code><span class="code-snippet_outer"> synchronized (this) {</span></code><code><span class="code-snippet_outer"> counter++;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ... // 非同步操作</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer">private volatile int counter = 0;</span></code><code><span class="code-snippet_outer">public void access(Long userId) {</span></code><code><span class="code-snippet_outer"> synchronized (this) {</span></code><code><span class="code-snippet_outer"> counter++;</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer"> ... // 非同步操作</span></code><code><span class="code-snippet_outer">}</span> 10.4.尽量合并为同一同步代码块 同步代码块是有性能开销的,如果确定可以合并为同一同步代码块,就应该尽量合并为同一同步代码块。 反例: <span class="code-snippet_outer">// 处理单一订单</span></code><code><span class="code-snippet_outer">public synchronized handleOrder(OrderDO order) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code> </code><code><span class="code-snippet_outer">// 处理所有订单</span></code><code><span class="code-snippet_outer">public void handleOrder(List<OrderDO> orderList) {</span></code><code><span class="code-snippet_outer"> for (OrderDO order : orderList) {</span></code><code><span class="code-snippet_outer"> handleOrder(order);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 12 <span class="code-snippet_outer">// 处理单一订单</span></code><code><span class="code-snippet_outer">public synchronized handleOrder(OrderDO order) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code></code><code><span class="code-snippet_outer">// 处理所有订单</span></code><code><span class="code-snippet_outer">public void handleOrder(List<OrderDO> orderList) {</span></code><code><span class="code-snippet_outer"> for (OrderDO order : orderList) {</span></code><code><span class="code-snippet_outer"> handleOrder(order);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer">// 处理单一订单</span></code><code><span class="code-snippet_outer">public handleOrder(OrderDO order) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code> </code><code><span class="code-snippet_outer">// 处理所有订单</span></code><code><span class="code-snippet_outer">public synchronized void handleOrder(List<OrderDO> orderList) {</span></code><code><span class="code-snippet_outer"> for (OrderDO order : orderList) {</span></code><code><span class="code-snippet_outer"> handleOrder(order);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 12 <span class="code-snippet_outer">// 处理单一订单</span></code><code><span class="code-snippet_outer">public handleOrder(OrderDO order) {</span></code><code><span class="code-snippet_outer"> ...</span></code><code><span class="code-snippet_outer">}</span></code><code></code><code><span class="code-snippet_outer">// 处理所有订单</span></code><code><span class="code-snippet_outer">public synchronized void handleOrder(List<OrderDO> orderList) {</span></code><code><span class="code-snippet_outer"> for (OrderDO order : orderList) {</span></code><code><span class="code-snippet_outer"> handleOrder(order);</span></code><code><span class="code-snippet_outer"> }</span></code><code><span class="code-snippet_outer">}</span> 10.5.尽量使用线程池减少线程开销 多线程中两个必要的开销:线程的创建和上下文切换。采用线程池,可以尽量地避免这些开销。 反例: <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">void</span> <span class="code-snippet__title">executeTask</span>(<span class="code-snippet__params">Runnable runnable</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">new</span> Thread(runnable).start();</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">void</span> <span class="code-snippet__title">executeTask</span>(<span class="code-snippet__params">Runnable runnable</span>)</span> {</span></code><code><span class="code-snippet_outer"> <span class="code-snippet__keyword">new</span> Thread(runnable).start();</span></code><code><span class="code-snippet_outer">}</span> 正例: <span class="code-snippet_outer"><span class="code-snippet__keyword">private</span> <span class="code-snippet__keyword">static</span> <span class="code-snippet__keyword">final</span> ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(<span class="code-snippet__number">10</span>);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">void</span> <span class="code-snippet__title">executeTask</span><span class="code-snippet__params">(Runnable runnable)</span> </span>{</span></code><code><span class="code-snippet_outer"> executorService.execute(runnable);</span></code><code><span class="code-snippet_outer">}</span> 1 <span class="code-snippet_outer"><span class="code-snippet__keyword">private</span> <span class="code-snippet__keyword">static</span> <span class="code-snippet__keyword">final</span> ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(<span class="code-snippet__number">10</span>);</span></code><code><span class="code-snippet_outer"><span class="code-snippet__function"><span class="code-snippet__keyword">public</span> <span class="code-snippet__keyword">void</span> <span class="code-snippet__title">executeTask</span><span class="code-snippet__params">(Runnable runnable)</span> </span>{</span></code><code><span class="code-snippet_outer"> executorService.execute(runnable);</span></code><code><span class="code-snippet_outer">}</span> 后记 作为一名长期奋战在业务一线的”IT民工”,没有机会去研究什么高深莫测的”理论”,只能专注于眼前看得见摸得着的”技术”,致力于做到”干一行、爱一行、专一行、精一行”。