1、避免创建不必要的对象
创建对象从来都不应该是一件随意的事情,因为创建一个对象就意味着垃圾回收器需要回收一个对象,而这两步操作都是需要消耗时间的。虽说创建一个对象的代价确实非常小,并且Android 2.3版本当中又增加了并发垃圾回收器机制,这让GC操作时的停顿时间也变得难以察觉,但是这些理由都不足以让我们可以肆意地创建对象,需要创建的对象我们自然要创建,但是不必要的对象我们就应该尽量避免创建。
代码块一:
- List<String> tempList = new ArrayList<String>();
- String value = "";
- for(int i=0;i<20;i++){
- value = ""+i;
- tempList.add(value);
- }
- value = null;
- List<String> tempList = new ArrayList<String>();
- for(int i=0;i<20;i++){
- String value = ""+i;
- tempList.add(value);
- }
2、静态比抽象要优
如果你并不需要访问一个对象中的某些字段,只是想调用它的某个方法来去完成一项通用的功能,那么可以将这个方法设置成静态方法,这会让调用的速度提升15%-20%,同时也不用为了调用这个方法而去专门创建对象了,这样还满足了上面的一条原则。另外这也是一种好的编程习惯,因为我们可以放心地调用静态方法,而不用担心调用这个方法后是否会改变对象的状态(静态方法内无法访问非静态字段)。
- private static int tempValue = 1;
- public static int getValue1(){
- return tempValue;
- }
- public int getValue2(){
- return tempValue;
- }
3、使用增强型for循环语法
增强型for循环(也被称为for-each循环)可以用于去遍历实现Iterable接口的集合以及数组,这是jdk 1.5中新增的一种循环模式。当然除了这种新增的循环模式之外,我们仍然还可以使用原有的普通循环模式。
代码块一:
- for(int i=0;i<tempList.size();i++){
- System.out.println("-----tempList:"+tempList.get(i));
- }
- int len = tempList.size();
- for(int i=0;i<len;i++){
- System.out.println("-----tempList:"+tempList.get(i));
- }
- for (String string : tempList) {
- System.out.println("-----tempList:"+string);
- }
4、避免在内部调用Getter/Setter方法
因为字段搜寻要比方法调用效率高得多,我们直接访问某个字段可能要比通过getters方法来去访问这个字段快3到7倍。不过我们肯定不能仅仅因为效率的原因就将封装这个技巧给抛弃了,编写代码还是要按照面向对象思维的,但是我们可以在能优化的地方进行优化,比如说避免在内部调用getter/setter方法。
- private int value = 1;
- public int getValue() {
- return value;
- }
- public void setValue(int value) {
- this.value = value;
- }
- //setValue(12); 不建议这么使用
- value = 12;
- //int tt = getValue(); 不建议这么使用
- int tt = value;