android的一些简单优化

来源:互联网 发布:手机淘宝店铺在哪里 编辑:程序博客网 时间:2024/06/07 17:42

1 .如果不仅需要遍历元素,而且需要元素的位置,就一定要使用数组或者 ArrayList ,因为所
有其他 Collection 类在这些情况下会更慢。
一般情况下,如果在读取元素几乎不变的数据集时对性能要求很高,建议使用常规数组。然
而,数组的大小固定,添加数据会影响性能

迭代遍历集合

List<Integer> lstint = new ArrayList<Integer>();  lstint.add(1);  lstint.add(2);  lstint.add(3);  // Iterator遍历一  Iterator<Integer> iterator = lstint.iterator();  while (iterator.hasNext())  {   int i = (Integer) iterator.next();   System.out.println(i);  }  // Iterator遍历二  for (Iterator<Integer> it = lstint.iterator(); it.hasNext();)  {   int i = (Integer) it.next();   System.out.println(i);  }

2 . 在一个线程中获取网络上的数据,在另一个线程(操作UI的主线程)中把这些数据展现给用户。
这种模式称为生产者/消费者模式

使用标准的 LinkedList实现线程安全队列的代码

public class ThreadSafeQueue {private LinkedList<String> mList = new LinkedList<String>();private final Object mLock = new Object();public void offer(String value) {        synchronized (mLock) {        mList.offer(value);        mLock.notifyAll();            }        }public synchronized String poll() {        synchronized (mLock) {        while(mList.isEmpty()) {        try {        mLock.wait();        } catch (InterruptedException e) {        // 简洁起见忽略异常处理            }        }        return mList.poll();        }    }}
LinkedBlockingQueue<String> blockingQueue =new LinkedBlockingQueue<String>();

上面的一行代码能像前面的例子一样提供相同类型的阻塞队列,甚至能提供额外的线程安全操作.
java.util.concurrent包含许多可选的队列以及并发映射类,所以,一般情况下,建议使用它们,
而不是像之前的示例那样使用更多代码。

3 .有时候无法避免在循环中创建对象,所以需要采用某种方法处理这种情况。解
决方案是使用一个静态工厂方法按需分配对象

public final class Pair {public int firstValue;public int secondValue;// 引用对象池中的下一个对象private Pair next;// 同步锁private static final Object sPoolSync = new Object();// 对象池中第一个可用的对象private static Pair sPool;private static int sPoolSize = 0;private static final int MAX_POOL_SIZE = 50;/*** 只能用obtain()方法获取对象*/private Pair() { }/*** 返回回收的对象或者当对象池为空时创建一个新对象*/public static Pair obtain() {        synchronized (sPoolSync) {        if (sPool != null) {        Pair m = sPool;        sPool = m.next;        m.next = null;        sPoolSize--;        return m;            }        }    return new Pair();}/*** 回收该对象。调用该方法后需要释放所有对该实例的引用*/public void recycle() {        synchronized (sPoolSync) {        if (sPoolSize < MAX_POOL_SIZE) {        next = sPool;        sPool = this;        sPoolSize++;                  }          }    }}

本例增加了多个字段,有静态的也有非静态的。可使用这些字段实现传统的 Pair 对象链表。只能通过 obtain 方法创建该类的对象。通过使用私有构造函数来防止在类外面创建对象。 obtain 方法首先会检查对象池中是否包含任何存在的对象,并删除列表中的第一个元素然后返回它。如果对象池为空, obtain 方法会创建一个新的对象。要把对象重新放回池中,需要在使用完该对象时,对它调用 recycle 方法。这时,不能再有对该对象的引用。

for (int i = 0; i < pairs.length; i+=2) {Pair pair = Pair.obtain();pair.firstValue = pairs[i];}

第一次运行这个方法会创建一个新的 Pair 实例,接下来的每次迭代会重用改对象。不过,下次再运行该方法时,不会再创建新的对象。另外,由于 obtain 和 recycle 是线程安全的,可以在多个并发线程中安全地使用这两个方法。唯一的缺点是,必须记住要手动调用 recycle 方法,不过这是一个很小的代价。这样就只会在应用退出时才会对 Pair 类进行垃圾回收。

0 0
原创粉丝点击