• 代码规范


    1.常量 & 变量

      1.1 直接赋值常量值,禁止声明新对象

        Long i = 1L;

        String s = "abc";

      1.2 尽量使用基本数据类型,避免自动装箱和拆箱(装箱和拆箱都是需要 CPU 和内存资源的,所以应尽量避免使用自动装箱和拆箱)

        int sum = 0;

      1.3 如果变量的初值会被覆盖,就没有必要给变量赋初值

        List<UserDO> userList;

        if (isAll) {

          userList = userDAO.queryAll();

        } else {

          userList = userDAO.queryActive();

        }

    2.对象 & 类

      2.1 采用 Lambda 表达式替换内部匿名类(相对于匿名内部类在效率上会更高一些)

        反例:

          List<User> userList = ...;

          Collections.sort(userList, new Comparator<User>() {

            @Override

            public int compare(User user1, User user2) {

              Long userId1 = user1.getId();

              Long userId2 = user2.getId();

              ....

              return userId1.compareTo(userId2);

            }

          });

        正例:

          List<User> userList = ...;

          Collections.sort(userList, (user1, user2) -> {

            Long userId1 = user1.getId();

            Long userId2 = user2.getId();

            .....

            return userId1.compareTo(userId2);

          });

    3. 表达式

      3.1 对于多常量选择分支,尽量使用 switch 语句而不是 if-else 语句(如果业务复杂,可以采用 Map 实现策略模式) 

      反例: 

        if (i == 1) {

          ...; // 分支 1

        } else if (i == 2) {

          ...; // 分支 2

        } else if (i == ...) {

          ...; // 分支 n

        } else {

          ...; // 分支 n+1

        }

      正例:

        switch (i) {

          case 1 :

            ... // 分支 1

            break;

          case 2 :

            ... // 分支 2

            break;

          case ... :

            ... // 分支 n

            break;

          default :

            ... // 分支 n+1

            break;

          }

     4.字符串

      4.1 尽量使用 StringBuilder 进行字符串拼接(String 是 final 类,内容不可修改,所以每次字符串拼接都会生成一个新对象。StringBuilder 在初始化时申请了一块内存,以后的字            符串拼接都在这块内存中执行,不会申请新内存和生成新对象。)

        StringBuilder sb = new StringBuilder(128);

        for (int i = 0; i < 10; i++) {

          if (i != 0) {

            sb.append(',');

          }

          sb.append(i);

        }

      4.2 不要使用 ""+ 转化字符串:(使用 ""+ 进行字符串转化,使用方便但是效率低,建议使用 String.valueOf)

        int i = 12345;

        String s = String.valueOf(i);

    5.数组

      

  • 相关阅读:
    MySQL中的内置系统函数
    Mysql导出表结构及表数据 mysqldump用法
    MySQL事务处理案例演示
    mysql中int、bigint、smallint 和 tinyint的区别详细介绍
    mysql 获取上个月,这个月的第一天或最后一天
    ★MySQL一些很重要的SQL语句
    remix的使用
    nodejs部署智能合约的方法-web3 0.20版本
    js同步-异步-回调
    ganache与metamask
  • 原文地址:https://www.cnblogs.com/Life-is-Demo/p/12167883.html
Copyright © 2020-2023  润新知