Java 代码的精优化

一、避免使用BigDecimal(double)

BigDecimal(double) 存在精度损失风险,在精确计算或值比较的场景中可能会导致业务逻辑异常。

 反例:

// BigDecimal 反例   
    BigDecimal  decimal = new BigDecimal(11.801D);
    System.out.println("decimal:"+decimal);

正例:

// BigDecimal 正例
    BigDecimal  bDecimal = BigDecimal.valueOf(11.801D);
    System.out.print("bDecimal:"+bDecimal);

执行结果:

    decimal:11.8010000000000001563194018672220408916473388671875
    bDecimal:11.801

二、String.split(String regex)部分关键字需要转译

使用字符串String 的plit 方法时,传入的分隔字符串是正则表达式,则部分关键字(比如 .[]()| 等)需要转义。

2.1 

String str = "small.sun.shine";
String[] strSplit = str.split(".");  // .需要转义,反例
String[] strSplit1 = str.split("\.");// 正例
String[] strSplit2 = str.split("[.]");// 正例
System.out.println("strSplit:" + Arrays.toString(strSplit));
System.out.println("strSplit1:" + Arrays.toString(strSplit1));
System.out.println("strSplit2:" + Arrays.toString(strSplit2));

执行结果:

strSplit:[]
strSplit1:[small, sun, shine]
strSplit2:[small, sun, shine]

2.2

String str = "small|sun|shine";
String[] strSplit = str.split("|");  // | 需要转义,反例
String[] strSplit1 = str.split("\|");// 正例
String[] strSplit2 = str.split("[|]");// 正例
System.out.println("strSplit:" + Arrays.toString(strSplit));
System.out.println("strSplit1:" + Arrays.toString(strSplit1));
System.out.println("strSplit2:" + Arrays.toString(strSplit2));

执行结果:

strSplit:[]
strSplit1:[small, sun, shine]
strSplit2:[small, sun, shine]

三、迭代entrySet() 获取Map 的key 和value

当循环中只需要获取Map 的主键key时,迭代keySet() 是正确的;但是,当需要主键key 和取值value 时,迭代entrySet() 才是更高效的做法,其比先迭代keySet() 后再去通过get 取值性能更佳。

反例:
//Map 获取value 反例:
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()){
    String value = map.get(key);
}

正例:

//Map 获取key & value 正例:
HashMap<String, String> map = new HashMap<>();
for (Map.Entry<String,String> entry : map.entrySet()){
    String key = entry.getKey();
    String value = entry.getValue();
}

四、MyBatis 不要为了多个查询条件而写 1 = 1

当遇到多个查询条件,使用where 1=1 可以很方便的解决我们的问题,但是这样很可能会造成非常大的性能损失,因为添加了 “where 1=1 ”的过滤条件之后,数据库系统就无法使用索引等查询优化策略,数据库系统将会被迫对每行数据进行扫描(即全表扫描) 以比较此行是否满足过滤条件,当表中的数据量较大时查询速度会非常慢;此外,还会存在SQL 注入的风险。

反例:

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
 select count(*) from t_rule_BookInfo t where 1=1
<if test="title !=null and title !='' ">
 AND title = #{title} 
</if> 
<if test="author !=null and author !='' ">
 AND author = #{author}
</if> 
</select>

正例:

<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
 select count(*) from t_rule_BookInfo t
<where>
<if test="title !=null and title !='' ">
 title = #{title} 
</if>
<if test="author !=null and author !='' "> 
 AND author = #{author}
</if>
</where> 
</select>
缘于生活,而归于工作。本人所书,而意于分享。 如有转载,请注明出处! --活出自己范儿
原文地址:https://www.cnblogs.com/Small-sunshine/p/11750945.html