5.4.2 方法被调用的次数
考虑方法的性能时,除了方法本身的执行速度要很快以外,方法本身被其他方法调用的次数也是很重要的。事实上,顶层的方法执行速度稍微慢一点通常问题都不大,而底层的方法其执行速度必须要快,否则就可能导致性能不佳,因为底层方法通常被调用次数比较多,而顶层方法被调用次数一般很少。
这里其实包含了两点:
1.可能被大量调用的底层方法,其执行速度必须非常快,这样才能保证整个系统的性能是可接受的。
2.顶层的方法要注意尽可能地减少调用底层方法的次数,尤其是应当尽可能地避免循环调用底层方法。
来看看下面的这个例子,这个例子是模拟将一些记录分页进行显示,每页最多显示20条记录,例子中总共1000条记录,显示第11页的记录,跟现实的情况比较接近。这个例子一共包含3个类:RepeatedInvoke、InfoPageDao和PageInfo,代码如下。
代码5.15 RepeatedInvoke类 01 import java.util.Vector; 02 03 public class RepeatedInvoke { 04 05 public static void main(String args[]) { 06 try { 07 int pagenum=11; 08 int size; 09 RepeatedInvoke ri=new RepeatedInvoke(); 10 Vector currentpage; 11 currentpage=ri.getCurrentPage(pagenum); 12 for(int index=0;index<currentpage.size();index++){ 13 System.out.println(((PageInfo)(currentpage.get (index))). getTitle()); 14 System.out.println(((PageInfo)(currentpage.get (index))). getContent()); 15 } 16 } catch (Throwable e) { 17 System.err.println("exception"); 18 } 19 } 20 21 public Vector getCurrentPage(int pagenum) throws Exception { 22 // 每页显示的记录数 23 int countperpage = 20; 24 // 总的记录数 25 int totalSize = getTotalPage().size(); 26 // 储存当前页 27 Vector currentpagev = new Vector(); 28 29 if (totalSize % countperpage > 0) { 30 // 总页数 31 int totalpagenum = totalSize / countperpage + 1; 32 } 33 34 35 36 for (int j = 0; j < getTotalPage().size(); j++) { 37 if ((j >= (pagenum - 1) * countperpage) 38 && (j < pagenum * countperpage)) { 39 currentpagev.addElement(getTotalPage().get(j)); 40 } 41 // 当currentpagev记录数等于每页显示记录数, 42 // 停止往currentpagev中添加记录 43 if (currentpagev.size() == countperpage) { 44 break; 45 } 46 } 47 return currentpagev; 48 } 49 50 private Vector getTotalPage() throws Exception { 51 // 从数据库获取所有记录数 52 InfoPageDao dao = new InfoPageDao(); 53 return dao.getPageResult("Product.getTolalPage"); 54 } 55 } |
代码5.16 InfoPageDao类 01 import java.util.Vector; 02 03 04 public class InfoPageDao { 05 06 private static int count = 0; 07 08 public Vector getPageResult(String string) throws Exception { 09 if(string == "Product.getTolalPage"){ 10 Vector v = new Vector(); 11 for(int i=0;i<1000;i++){ 12 PageInfo info = new PageInfo(); 13 info.setTitle(count+"\ttitle"); 14 info.setContent(count+"\tcontent"); 15 count ++; 16 v.add(info); 17 } 18 count = 0; 19 return v; 20 } 21 else{ 22 throw new Exception("unsupport"); 23 } 24 25 } 26 27 } |