1.使用位移操作替代乘除法
计算机是使用二进制表示的,位移操作会极大地提高性能。
<< 左移相当于乘以 2;>> 右移相当于除以 2;
>>> 无符号右移相当于除以 2,但它会忽略符号位,空位都以 0 补齐。
a = val << 3;
b = val >> 1;
2.尽量减少对变量的重复计算
我们知道对方法的调用是有消耗的,包括创建栈帧、调用方法时保护现场,恢复现场等。
//反例
for (int i = 0; i < list.size(); i++) {
System.out.println("result");
}
//正例
for (int i = 0, length = list.size(); i < length; i++) {
System.out.println("result");
}
在**list.size()**很大的时候,就减少了很多的消耗。
3.不要捕捉RuntimeException
RuntimeException 不应该通过 catch 语句去捕捉,而应该使用编码手段进行规避。
如下面的代码,list 可能会出现数组越界异常。
是否越界是可以通过代码提前判断的,而不是等到发生异常时去捕捉。
提前判断这种方式,代码会更优雅,效率也更高。
//反例
public String test1(List<String> list, int index) {
try {
return list.get(index);
} catch (IndexOutOfBoundsException ex) {
return null;
}
}
//正例
public String test2(List<String> list, int index) {
if (index >= list.size() || index < 0) {
return null;
}
return list.get(index);
}
3.使用局部变量可避免在堆上分配
由于堆资源是多线程共享的,是垃圾回收器工作的主要区域,过多的对象会造成 GC 压力,可以通过局部变量的方式,将变量在栈上分配。这种方式变量会随着方法执行的完毕而销毁,能够减轻 GC 的压力。
4.减少变量的作用范围
注意变量的作用范围,尽量减少对象的创建。
如下面的代码,变量 s 每次进入方法都会创建,可以将它移动到 if 语句内部。
public void test(String str) {
final int s = 100;
if (!StringUtils.isEmpty(str)) {
int result = s * s;
}
}
5.尽量采用懒加载的策略,在需要的时候才创建
String str = "月伴飞鱼";
if (name == "公众号") {
list.add(str);
}
if (name == "公众号") {
String str = "月伴飞鱼";
list.add(str);
}
6.访问静态变量直接使用类名
使用对象访问静态变量,这种方式多了一步寻址操作,需要先找到变量对应的类,再找到类对应的变量。
// 反例
int i = objectA.staticMethod();
// 正例
int i = ClassA.staticMethod();
7.字符串拼接使用StringBuilder
字符串拼接,使用 StringBuilder 或者 StringBuffer,不要使用 + 号。
//反例
public class StringTest {
@Test
public void testStringPlus() {
String str = "111";
str += "222";
str += "333";
System.out.println(str);
}
}
//正例
public class TestMain {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("111");
sb.append("222");
sb.append(333);
System.out.println(sb.toString());
}
}
10.循环内不要不断创建对象引用
//反例
for (int i = 1; i <= size; i++) {
Object obj = new Object();
}
//正例
Object obj = null;
for (int i = 0; i <= size; i++) {
obj = new Object();
}
第一种会导致内存中有size个Object对象引用存在,size很大的话,就耗费内存了