如何优化功能模块的业务代码:
1、减少使用static修饰变量和方法。
2、减少使用全局变量。
3、控制public方法的形参在3个以内,多了最好用实体类来代替。创建实体类,将形参作为实体类的字段来写。
4、for循环里面不要写try..catch,需要写在外面。
5、for循环内不要不断创建对象引用。例:
for (int i = 1; i <= count; i++){
Object obj = new Object();
}
优化:
Object obj = null;
for (int i = 0; i <= count; i++)
{
obj = new Object();
}
6、for循环的写法 ,减少对变量的计算。例:
for (int i = 0; i < list.size(); i++)
{...}
优化:
for (int i = 0, length = list.size(); i < length; i++)
{...}
7、采用懒加载机制,需要的时候才创建。例:
String str = "aaa";
if (i == 1)
{
list.add(str);
}
优化:
if (i == 1)
{
String str = "aaa";
list.add(str);
}
8、当复制大量数据的时候,可以使用System.arraycopy()命令。
9、不要创建一些不使用的对象。
10、只用equals比较的时候,将变量写在前面。例:
String str = "123";
if (str.equals("123")) {...}
优化:
String str = "123";
if ("123".equals(str)) {...}
11、不要对超出数据基本类型大小范围作向下转型。long 转int,结果意想不到。
12、使用最有效率的方式遍历Map。例:
public static void main(String[] args)
{
HashMap hm = new HashMap();
hm.put("111", "222");Set> entrySet = hm.entrySet();
Iterator> iter = entrySet.iterator(); while (iter.hasNext())
{
Map.Entry entry = iter.next();
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
13、尽量使用基本数据类型代替对象。例:
String str = "hello";
优化:
String str = new String("hello");
14、多线程在未发生线程安全的前提下,建议使用HashMap和ArrayList。因为HashTable和vector使用了同步机制,降低了性能。
15、尽量在finally中释放资源,因为finally代码块中的代码总会执行,可以确保资源关闭。
16、在创建容器的时候,尽量确定他们的大小。StringBuffer sb = new StringBuffer(1000);
17、查询用ArrayList,增删用LinkedList。