其他
Java工程师该如何编写高效代码?
阿里妹导读:世界上只有两种物质:高效率和低效率;世界上只有两种人:高效率的人和低效率的人。——萧伯纳
1.常量&变量
1.1.直接赋值常量值,禁止声明新对象
Long i = new Long(1L);
String s = new String("abc");
Long i = 1L;
String s = "abc";
1.2.当成员变量值无需改变时,尽量定义为静态常量
public class HttpConnection {
private final long timeout = 5L;
...
}
public class HttpConnection {
private static final long TIMEOUT = 5L;
...
}
1.3.尽量使用基本数据类型,避免自动装箱和拆箱
Integer sum = 0;
int[] values = ...;
for (int value : values) {
sum += value; // 相当于result = Integer.valueOf(result.intValue() + value);
}
int sum = 0;
int[] values = ...;
for (int value : values) {
sum += value;
}
1.4.如果变量的初值会被覆盖,就没有必要给变量赋初值
List<UserDO> userList = new ArrayList<>();
if (isAll) {
userList = userDAO.queryAll();
} else {
userList = userDAO.queryActive();
}
List<UserDO> userList;
if (isAll) {
userList = userDAO.queryAll();
} else {
userList = userDAO.queryActive();
}
1.5.尽量使用函数内的基本类型临时变量
public final class Accumulator {
private double result = 0.0D;
public void addAll(@NonNull double[] values) {
for(double value : values) {
result += value;
}
}
...
}
public final class Accumulator {
private double result = 0.0D;
public void addAll(@NonNull double[] values) {
double sum = 0.0D;
for(double value : values) {
sum += value;
}
result += sum;
}
...
}
1.6.尽量不要在循环体外定义变量
UserVO userVO;
List<UserDO> userDOList = ...;
List<UserVO> userVOList = new ArrayList<>(userDOList.size());
for (UserDO userDO : userDOList) {
userVO = new UserVO();
userVO.setId(userDO.getId());
...
userVOList.add(userVO);
}
List<UserDO> userDOList = ...;
List<UserVO> userVOList = new ArrayList<>(userDOList.size());
for (UserDO userDO : userDOList) {
UserVO userVO = new UserVO();
userVO.setId(userDO.getId());
...
userVOList.add(userVO);
}
1.7.不可变的静态常量,尽量使用非线程安全类
public static final Map<String, Class> CLASS_MAP;
static {
Map<String, Class> classMap = new ConcurrentHashMap<>(16);
classMap.put("VARCHAR", java.lang.String.class);
...
CLASS_MAP = Collections.unmodifiableMap(classMap);
}
public static final Map<String, Class> CLASS_MAP;
static {
Map<String, Class> classMap = new HashMap<>(16);
classMap.put("VARCHAR", java.lang.String.class);
...
CLASS_MAP = Collections.unmodifiableMap(classMap);
}
1.8.不可变的成员变量,尽量使用非线程安全类
@Service
public class StrategyFactory implements InitializingBean {
@Autowired
private List<Strategy> strategyList;
private Map<String, Strategy> strategyMap;
@Override
public void afterPropertiesSet() {
if (CollectionUtils.isNotEmpty(strategyList)) {
int size = (int) Math.ceil(strategyList.size() * 4.0 / 3);
Map<String, Strategy> map = new ConcurrentHashMap<>(size);
for (Strategy strategy : strategyList) {
map.put(strategy.getType(), strategy);
}
strategyMap = Collections.unmodifiableMap(map);
}
}
...
}
@Service
public class StrategyFactory implements InitializingBean {
@Autowired
private List<Strategy> strategyList;
private Map<String, Strategy> strategyMap;
@Override
public void afterPropertiesSet() {
if (CollectionUtils.isNotEmpty(strategyList)) {
int size = (int) Math.ceil(strategyList.size() * 4.0 / 3);
Map<String, Strategy> map = new HashMap<>(size);
for (Strategy strategy : strategyList) {
map.put(strategy.getType(), strategy);
}
strategyMap = Collections.unmodifiableMap(map);
}
}
...
2.对象&类
2.1.禁止使用JSON转化对象
List<UserDO> userDOList = ...;
List<UserVO> userVOList = JSON.parseArray(JSON.toJSONString(userDOList), UserVO.class);
List<UserDO> userDOList = ...;
List<UserVO> userVOList = new ArrayList<>(userDOList.size());
for (UserDO userDO : userDOList) {
UserVO userVO = new UserVO();
userVO.setId(userDO.getId());
...
userVOList.add(userVO);
}
2.2.尽量不使用反射赋值对象
List<UserDO> userDOList = ...;
List<UserVO> userVOList = new ArrayList<>(userDOList.size());
for (UserDO userDO : userDOList) {
UserVO userVO = new UserVO();
BeanUtils.copyProperties(userDO, userVO);
userVOList.add(userVO);
}
List<UserDO> userDOList = ...;
List<UserVO> userVOList = new ArrayList<>(userDOList.size());
for (UserDO userDO : userDOList) {
UserVO userVO = new UserVO();
userVO.setId(userDO.getId());
...
userVOList.add(userVO);
}
2.3.采用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);
});
2.4.尽量避免定义不必要的子类
public static final Map<String, Class> CLASS_MAP =
Collections.unmodifiableMap(new HashMap<String, Class>(16) {
private static final long serialVersionUID = 1L;
{
put("VARCHAR", java.lang.String.class);
}
});
public static final Map<String, Class> CLASS_MAP;
static {
Map<String, Class> classMap = new HashMap<>(16);
classMap.put("VARCHAR", java.lang.String.class);
...
CLASS_MAP = Collections.unmodifiableMap(classMap);
}
2.5.尽量指定类的final修饰符
public class DateHelper {
...
}
public final class DateHelper {
...
}
3.方法
3.1.把跟类成员变量无关的方法声明成静态方法
public int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
3.2.尽量使用基本数据类型作为方法参数类型,避免不必要的装箱、拆箱和空指针判断
public static double sum(Double value1, Double value2) {
double double1 = Objects.isNull(value1) ? 0.0D : value1;
double double2 = Objects.isNull(value2) ? 0.0D : value2;
return double1 + double2;
}
double result = sum(1.0D, 2.0D);
public static double sum(double value1, double value2) {
return value1 + value2;
}
double result = sum(1.0D, 2.0D);
3.3.尽量使用基本数据类型作为方法返回值类型,避免不必要的装箱、拆箱和空指针判断
public static Boolean isValid(UserDO user) {
if (Objects.isNull(user)) {
return false;
}
return Boolean.TRUE.equals(user.getIsValid());
}
// 调用代码
UserDO user = ...;
Boolean isValid = isValid(user);
if (Objects.nonNull(isValid) && isValid.booleanValue()) {
...
}
public static boolean isValid(UserDO user) {
if (Objects.isNull(user)) {
return false;
}
return Boolean.TRUE.equals(user.getIsValid());
}
// 调用代码
UserDO user = ...;
if (isValid(user)) {
...
}
3.4.协议方法参数值非空,避免不必要的空指针判断
public static boolean isValid(UserDO user) {
if (Objects.isNull(user)) {
return false;
}
return Boolean.TRUE.equals(user.getIsValid());
}
public static boolean isValid(@NonNull UserDO user) {
return Boolean.TRUE.equals(user.getIsValid());
}
3.5.协议方法返回值非空,避免不必要的空指针判断
// 定义接口
public interface OrderService {
public List<OrderVO> queryUserOrder(Long userId);
}
// 调用代码
List<OrderVO> orderList = orderService.queryUserOrder(userId);
if (CollectionUtils.isNotEmpty(orderList)) {
for (OrderVO order : orderList) {
...
}
}
// 定义接口
public interface OrderService {
@NonNull
public List<OrderVO> queryUserOrder(Long userId);
}
// 调用代码
List<OrderVO> orderList = orderService.queryUserOrder(userId);
for (OrderVO order : orderList) {
...
}
3.6.被调用方法已支持判空处理,调用方法无需再进行判空处理
UserDO user = null;
if (StringUtils.isNotBlank(value)) {
user = JSON.parseObject(value, UserDO.class);
}
UserDO user = JSON.parseObject(value, UserDO.class);
3.7.尽量避免不必要的函数封装
// 函数封装
public static boolean isVip(Boolean isVip) {
return Boolean.TRUE.equals(isVip);
}
// 使用代码
boolean isVip = isVip(user.getVip());
boolean isVip = Boolean.TRUE.equals(user.getVip());
3.8.尽量指定方法的final修饰符
public class Rectangle {
...
public double area() {
...
}
}
public class Rectangle {
...
public final double area() {
...
}
}
4.表达式
4.1.尽量减少方法的重复调用
List<UserDO> userList = ...;
for (int i = 0; i < userList.size(); i++) {
...
}
List<UserDO> userList = ...;
int userLength = userList.size();
for (int i = 0; i < userLength; i++) {
...
}
4.2.尽量避免不必要的方法调用
List<UserDO> userList = userDAO.queryActive();
if (isAll) {
userList = userDAO.queryAll();
}
List<UserDO> userList;
if (isAll) {
userList = userDAO.queryAll();
} else {
userList = userDAO.queryActive();
}
4.3.尽量使用移位来代替正整数乘除
int num1 = a * 4;
int num2 = a / 4;
int num1 = a << 2;
int num2 = a >> 2;
4.4.提取公共表达式,避免重复计算
double distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
double dx = x2 - x1;
double dy = y2 - y1;
double distance = Math.sqrt(dx * dx + dy * dy);
或
double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
4.5.尽量不在条件表达式中用!取反
if (!(a >= 10)) {
... // 条件处理1
} else {
... // 条件处理2
}
if (a < 10) {
... // 条件处理1
} else {
... // 条件处理2
}
4.6.对于多常量选择分支,尽量使用switch语句而不是if-else语句
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;
}
5.字符串
5.1.尽量不要使用正则表达式匹配
String source = "a::1,b::2,c::3,d::4";
String target = source.replaceAll("::", "=");
Stringp[] targets = source.spit("::");
String source = "a::1,b::2,c::3,d::4";
String target = source.replace("::", "=");
Stringp[] targets = StringUtils.split(source, "::");
5.2.尽量使用字符替换字符串
String source = "a:1,b:2,c:3,d:4";
int index = source.indexOf(":");
String target = source.replace(":", "=");
String source = "a:1,b:2,c:3,d:4";
int index = source.indexOf(':');
String target = source.replace(':', '=');
5.3.尽量使用StringBuilder进行字符串拼接
String s = "";
for (int i = 0; i < 10; i++) {
if (i != 0) {
s += ',';
}
s += i;
}
StringBuilder sb = new StringBuilder(128);
for (int i = 0; i < 10; i++) {
if (i != 0) {
sb.append(',');
}
sb.append(i);
}
5.4.不要使用""+转化字符串
int i = 12345;
String s = "" + i;
int i = 12345;
String s = String.valueOf(i);
6.数组
6.1.不要使用循环拷贝数组,尽量使用System.arraycopy拷贝数组
int[] sources = new int[] {1, 2, 3, 4, 5};
int[] targets = new int[sources.length];
for (int i = 0; i < targets.length; i++) {
targets[i] = sources[i];
}
int[] sources = new int[] {1, 2, 3, 4, 5};
int[] targets = new int[sources.length];
System.arraycopy(sources, 0, targets, 0, targets.length);
6.2.集合转化为类型T数组时,尽量传入空数组T[0]
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, ...);
Integer[] integers = integerList.toArray(new Integer[integerList.size()]);
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, ...);
Integer[] integers = integerList.toArray(new Integer[0]); // 勿用new Integer[]{}
6.3.集合转化为Object数组时,尽量使用toArray()方法
List<Object> objectList = Arrays.asList(1, "2", 3, "4", 5, ...);
Object[] objects = objectList.toArray(new Object[0]);
List<Object> objectList = Arrays.asList(1, "2", 3, "4", 5, ...);
Object[] objects = objectList.toArray();
7.集合
7.1.初始化集合时,尽量指定集合大小
List<UserDO> userDOList = ...;
Set<Long> userSet = new HashSet<>();
Map<Long, UserDO> userMap = new HashMap<>();
List<UserVO> userList = new ArrayList<>();
for (UserDO userDO : userDOList) {
userSet.add(userDO.getId());
userMap.put(userDO.getId(), userDO);
userList.add(transUser(userDO));
}
List<UserDO> userDOList = ...;
int userSize = userDOList.size();
Set<Long> userSet = new HashSet<>(userSize);
Map<Long, UserDO> userMap = new HashMap<>((int) Math.ceil(userSize * 4.0 / 3));
List<UserVO> userList = new ArrayList<>(userSize);
for (UserDO userDO : userDOList) {
userSet.add(userDO.getId());
userMap.put(userDO.getId(), userDO);
userList.add(transUser(userDO));
}
7.2.不要使用循环拷贝集合,尽量使用JDK提供的方法拷贝集合
List<UserDO> user1List = ...;
List<UserDO> user2List = ...;
List<UserDO> userList = new ArrayList<>(user1List.size() + user2List.size());
for (UserDO user1 : user1List) {
userList.add(user1);
}
for (UserDO user2 : user2List) {
userList.add(user2);
}
List<UserDO> user1List = ...;
List<UserDO> user2List = ...;
List<UserDO> userList = new ArrayList<>(user1List.size() + user2List.size());
userList.addAll(user1List);
userList.addAll(user2List);
7.3.尽量使用Arrays.asList转化数组为列表
List<String> typeList = new ArrayList<>(8);
typeList.add("Short");
typeList.add("Integer");
typeList.add("Long");
String[] names = ...;
List<String> nameList = ...;
for (String name : names) {
nameList.add(name);
}
List<String> typeList = Arrays.asList("Short", "Integer", "Long");
String[] names = ...;
List<String> nameList = ...;
nameList.addAll(Arrays.asList(names));
7.4.直接迭代需要使用的集合
Map<Long, UserDO> userMap = ...;
for (Long userId : userMap.keySet()) {
UserDO user = userMap.get(userId);
...
}
Map<Long, UserDO> userMap = ...;
for (Map.Entry<Long, UserDO> userEntry : userMap.entrySet()) {
Long userId = userEntry.getKey();
UserDO user = userEntry.getValue();
...
}
7.5.不要使用size方法检测空,必须使用isEmpty方法检测空
List<UserDO> userList = ...;
if (userList.size() == 0) {
...
}
Map<Long, UserDO> userMap = ...;
if (userMap.size() == 0) {
...
}
List<UserDO> userList = ...;
if (userList.isEmpty()) {
...
}
Map<Long, UserDO> userMap = ...;
if (userMap.isEmpty()) {
...
}
7.6.非随机访问的List,尽量使用迭代代替随机访问
LinkedList<UserDO> userDOList = ...;
int size = userDOList.size();
for (int i = 0; i < size; i++) {
UserDO userDO = userDOList.get(i);
...
}
LinkedList<UserDO> userDOList = ...;
for (UserDO userDO : userDOList) {
...
}
7.7.尽量使用HashSet判断值存在
List<Long> adminIdList = ...;
List<UserDO> userDOList = ...;
List<UserVO> userVOList = new ArrayList<>(userDOList.size());
for (UserDO userDO : userDOList) {
if (adminIdList.contains(userDO.getId())) {
userVOList.add(transUser(userDO));
}
}
Set<Long> adminIdSet = ...;
List<UserDO> userDOList = ...;
List<UserVO> userVOList = new ArrayList<>(userDOList.size());
for (UserDO userDO : userDOList) {
if (adminIdSet.contains(userDO.getId())) {
userVOList.add(transUser(userDO));
}
}
7.8.避免先判断存在再进行获取
public static UserVO transUser(UserDO user, Map<Long, RoleDO> roleMap) {
UserVO userVO = new UserVO();
userVO.setId(user.getId());
...
if (roleMap.contains(user.getRoleId())) {
RoleDO role = roleMap.get(user.getRoleId());
userVO.setRole(transRole(role));
}
}
public static UserVO transUser(UserDO user, Map<Long, RoleDO> roleMap) {
UserVO userVO = new UserVO();
userVO.setId(user.getId());
...
RoleDO role = roleMap.get(user.getRoleId());
if (Objects.nonNull(role)) {
userVO.setRole(transRole(role));
}
}
8.异常
8.1.直接捕获对应的异常
try {
saveData();
} catch (Exception e) {
if (e instanceof IOException) {
log.error("保存数据IO异常", e);
} else {
log.error("保存数据其它异常", e);
}
}
try {
saveData();
} catch (IOException e) {
log.error("保存数据IO异常", e);
} catch (Exception e) {
log.error("保存数据其它异常", e);
}
8.2.尽量避免在循环中捕获异常
public Double sum(List<String> valueList) {
double sum = 0.0D;
for (String value : valueList) {
try {
sum += Double.parseDouble(value);
} catch (NumberFormatException e) {
return null;
}
}
return sum;
}
public Double sum(List<String> valueList) {
double sum = 0.0D;
try {
for (String value : valueList) {
sum += Double.parseDouble(value);
}
} catch (NumberFormatException e) {
return null;
}
return sum;
}
8.3.禁止使用异常控制业务流程
public static boolean isValid(UserDO user) {
try {
return Boolean.TRUE.equals(user.getIsValid());
} catch(NullPointerException e) {
return false;
}
}
public static boolean isValid(UserDO user) {
if (Objects.isNull(user)) {
return false;
}
return Boolean.TRUE.equals(user.getIsValid());
}
9.缓冲区
9.1.初始化时尽量指定缓冲区大小
StringBuffer buffer = new StringBuffer();
StringBuilder builder = new StringBuilder();
StringBuffer buffer = new StringBuffer(1024);
StringBuilder builder = new StringBuilder(1024);
9.2.尽量重复使用同一缓冲区
StringBuilder builder1 = new StringBuilder(128);
builder1.append("update t_user set name = '").append(userName).append("' where id = ").append(userId);
statement.executeUpdate(builder1.toString());
StringBuilder builder2 = new StringBuilder(128);
builder2.append("select id, name from t_user where id = ").append(userId);
ResultSet resultSet = statement.executeQuery(builder2.toString());
...
StringBuilder builder = new StringBuilder(128);
builder.append("update t_user set name = '").append(userName).append("' where id = ").append(userId);
statement.executeUpdate(builder.toString());
builder.setLength(0);
builder.append("select id, name from t_user where id = ").append(userId);
ResultSet resultSet = statement.executeQuery(builder.toString());
...
9.3.尽量设计使用同一缓冲区
// 转化XML(UserDO)
public static String toXml(UserDO user) {
StringBuilder builder = new StringBuilder(128);
builder.append("<UserDO>");
builder.append(toXml(user.getId()));
builder.append(toXml(user.getName()));
builder.append(toXml(user.getRole()));
builder.append("</UserDO>");
return builder.toString();
}
// 转化XML(Long)
public static String toXml(Long value) {
StringBuilder builder = new StringBuilder(128);
builder.append("<Long>");
builder.append(value);
builder.append("</Long>");
return builder.toString();
}
...
// 使用代码
UserDO user = ...;
String xml = toXml(user);
// 转化XML(UserDO)
public static void toXml(StringBuilder builder, UserDO user) {
builder.append("<UserDO>");
toXml(builder, user.getId());
toXml(builder, user.getName());
toXml(builder, user.getRole());
builder.append("</UserDO>");
}
// 转化XML(Long)
public static void toXml(StringBuilder builder, Long value) {
builder.append("<Long>");
builder.append(value);
builder.append("</Long>");
}
...
// 使用代码
UserDO user = ...;
StringBuilder builder = new StringBuilder(1024);
toXml(builder, user);
String xml = builder.toString();
9.4.尽量使用缓冲流减少IO操作
try (FileInputStream input = new FileInputStream("a");
FileOutputStream output = new FileOutputStream("b")) {
int size = 0;
byte[] temp = new byte[1024];
while ((size = input.read(temp)) != -1) {
output.write(temp, 0, size);
}
} catch (IOException e) {
log.error("复制文件异常", e);
}
try (BufferedInputStream input = new BufferedInputStream(new FileInputStream("a"));
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("b"))) {
int size = 0;
byte[] temp = new byte[1024];
while ((size = input.read(temp)) != -1) {
output.write(temp, 0, size);
}
} catch (IOException e) {
log.error("复制文件异常", e);
}
10.线程
10.1.在单线程中,尽量使用非线程安全类
StringBuffer buffer = new StringBuffer(128);
buffer.append("select * from ").append(T_USER).append(" where id = ?");
StringBuilder buffer = new StringBuilder(128);
buffer.append("select * from ").append(T_USER).append(" where id = ?");
10.2.在多线程中,尽量使用线程安全类
private volatile int counter = 0;
public void access(Long userId) {
synchronized (this) {
counter++;
}
...
}
private final AtomicInteger counter = new AtomicInteger(0);
public void access(Long userId) {
counter.incrementAndGet();
...
}
10.3.尽量减少同步代码块范围
private volatile int counter = 0;
public synchronized void access(Long userId) {
counter++;
... // 非同步操作
}
private volatile int counter = 0;
public void access(Long userId) {
synchronized (this) {
counter++;
}
... // 非同步操作
}
10.4.尽量合并为同一同步代码块
// 处理单一订单
public synchronized handleOrder(OrderDO order) {
...
}
// 处理所有订单
public void handleOrder(List<OrderDO> orderList) {
for (OrderDO order : orderList) {
handleOrder(order);
}
}
// 处理单一订单
public handleOrder(OrderDO order) {
...
}
// 处理所有订单
public synchronized void handleOrder(List<OrderDO> orderList) {
for (OrderDO order : orderList) {
handleOrder(order);
}
}
10.5.尽量使用线程池减少线程开销
public void executeTask(Runnable runnable) {
new Thread(runnable).start();
}
private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);
public void executeTask(Runnable runnable) {
executorService.execute(runnable);
}