java 性能提升和代码优雅 从点滴做起

17 篇文章 0 订阅
13 篇文章 1 订阅

目录

1、Map 迭代 选用entrySet()

2、使用Collection.isEmpty()检测空

3、集合初始化尽量指定大小

4、字符串拼接使用 StringBuilder 

5、List 的随机访问

6、频繁调用 Collection.contains 方法使用 Set

7、使用 try-with-resources 语句

8、公有静态常量应该通过类访问

9、使用String.valueOf(value)代替""+value

10、过时代码添加 @Deprecated 注解

11、禁止使用构造方法 BigDecimal(double)

12、返回空数组和空集合而不是 null

13、枚举的属性字段必须是私有不可变

14、小心String.split(String regex)


1、Map 迭代 选用entrySet()

反例


Map<String, String> map = ...;
for (String key : map.keySet()) {
    String value = map.get(key);
    ...
}

正解:


Map<String, String> map = ...;
for (Map.Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    ...
}

2、使用Collection.isEmpty()检测空

反例:


if (collection.size() == 0) {
    ...
}

正解:

if (collection.isEmpty()) {
    ...
}

if (CollectionUtils.isEmpty(collection)) {
    ...
}
if (CollectionUtils.isNotEmpty(collection)) {
    ...
}

3、集合初始化尽量指定大小

每次扩容的时间复杂度很有可能是 O(n) ,所以尽量指定可预知的集合大小,能减少集合的扩容次数。

正解:

List<Integer> list = new ArrayList<>(100);

 

4、字符串拼接使用 StringBuilder 

正解:

StringBuilder sb = new StringBuilder();
sb.append("ssssss"); 
sb.append("ssssss"); 

5、List 的随机访问

大家都知道数组和链表的区别:数组的随机访问效率更高。当调用方法获取到 List 后,如果想随机访问其中的数据,并不知道该数组内部实现是链表还是数组,怎么办呢?可以判断它是否实现* RandomAccess *接口。

正解:

// 调用别人的服务获取到list
List<Integer> list = otherService.getList();
if (list instanceof RandomAccess) {
    // 内部数组实现,可以随机访问
    System.out.println(list.get(list.size() - 1));
} else {
    // 内部可能是链表实现,随机访问效率低
}

6、频繁调用 Collection.contains 方法使用 Set

在 java 集合类库中,List 的 contains 方法普遍时间复杂度是 O(n) ,如果在代码中需要频繁调用 contains 方法查找数据,可以先将 list 转换成 HashSet 实现,将 O(n) 的时间复杂度降为 O(1) 。

反例:

ArrayList<Integer> list = otherService.getList();
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    // 时间复杂度O(n)
    list.contains(i);
}

正解:

ArrayList<Integer> list = otherService.getList();
Set<Integer> set = new HashSet(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    // 时间复杂度O(1)
    set.contains(i);
}

7、使用 try-with-resources 语句

Java 7 中引入了 try-with-resources 语句,该语句能保证将相关资源关闭,优于原来的 try-catch-finally 语句,并且使程序代码更安全更简洁。

反例:

private void handle(String fileName) {
    BufferedReader reader = null;
    try {
        String line;
        reader = new BufferedReader(new FileReader(fileName));
        while ((line = reader.readLine()) != null) {
            ...
        }
    } catch (Exception e) {
        ...
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                ...
            }
        }
    }
}

正解:

 

private void handle(String fileName) {
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
        String line;
        while ((line = reader.readLine()) != null) {
            ...
        }
    } catch (Exception e) {
        ...
    }
}

8、公有静态常量应该通过类访问

反例:

public class User {
    public static final String CONST_NAME = "name";
    ...
}

User user = new User();
String nameKey = user.CONST_NAME;

正解:

public class User {
    public static final String CONST_NAME = "name";
    ...
}

String nameKey = User.CONST_NAME;

9、使用String.valueOf(value)代替""+value

当要把其它对象或类型转化为字符串时,使用 String.valueOf(value) 比""+value 的效率更高。

反例:

int i = 1;
String s = "" + i;

正解:

int i = 1;
String s = String.valueOf(i);

10、过时代码添加 @Deprecated 注解

当一段代码过时,但为了兼容又无法直接删除,不希望以后有人再使用它时,可以添加 @Deprecated 注解进行标记。在文档注释中添加 @deprecated 来进行解释,并提供可替代方案。

/**
 * @deprecated 此方法效率较低,请使用{@link newSave()}方法替换它
 */
@Deprecated
public void save(){
    // do something
}

11、禁止使用构造方法 BigDecimal(double)

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

反例:

BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115...

正解:

BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1

12、返回空数组和空集合而不是 null

返回 null ,需要调用方强制检测 null ,否则就会抛出空指针异常。返回空数组或空集合,有效地避免了调用方因为未检测 null 而抛出空指针异常,还可以删除调用方检测 null 的语句使代码更简洁。

public static Result[] getResults() {
    return new Result[0];
}

public static List<Result> getResultList() {
    return Collections.emptyList();
}

public static Map<String, Result> getResultMap() {
    return Collections.emptyMap();
}

13、枚举的属性字段必须是私有不可变

枚举通常被当做常量使用,如果枚举中存在公共属性字段或设置字段方法,那么这些枚举常量的属性很容易被修改。理想情况下,枚举中的属性字段是私有的,并在私有构造函数中赋值,没有对应的 Setter 方法,最好加上 final 修饰符。

反例:

public enum UserStatus {
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");


    public int value;
    private String description;


    private UserStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }


    public String getDescription() {
        return description;
    }


    public void setDescription(String description) {
        this.description = description;
    }
}

 

正解:


public enum UserStatus {
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");


    private final int value;
    private final String description;


    private UserStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }


    public int getValue() {
        return value;
    }


    public String getDescription() {
        return description;
    }
}

14、小心String.split(String regex)

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

反例:


"a.ab.abc".split("."); // 结果为[]
"a|ab|abc".split("|"); // 结果为["a", "|", "a", "b", "|", "a", "b", "c"]

正解:

"a.ab.abc".split("\\."); // 结果为["a", "ab", "abc"]
"a|ab|abc".split("\\|"); // 结果为["a", "ab", "abc"]

 

参照 :消灭 Java 代码的“坏味道”  

本文只截取了,我自己常犯的错误,便于记忆,想看原文去公众号看。

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值