代码改变世界

sqlserver2008中 count(*),count(1),count(id) 性能大比拼

2012-02-03 13:53  cluby  阅读(882)  评论(0)    收藏  举报

测试表 test

三个字段  id  number1  number2
总共有1660W 多 行记录 

select count(id) from test                                                             select count(id) from test  where id <=8000000               
 
 CPU 时间 = 2905 毫秒,占用时间 = 4078 毫秒。                       CPU 时间 = 1422 毫秒,占用时间 = 2002 毫秒。
 CPU 时间 = 2891 毫秒,占用时间 = 3985 毫秒。                       CPU 时间 = 1422 毫秒,占用时间 = 1969 毫秒。
 CPU 时间 = 3048 毫秒,占用时间 = 4076 毫秒。                       CPU 时间 = 1485 毫秒,占用时间 = 2058 毫秒。
 CPU平均 2948               占用时间平均4046.3                             CPU平均 1443               占用时间平均2009.6
select count(*) from test                                                              select count(*) from test  where id <=8000000     
 CPU 时间 = 2984 毫秒,占用时间 = 4043 毫秒。                         CPU 时间 = 1500 毫秒,占用时间 = 2056 毫秒。
 CPU 时间 = 2984 毫秒,占用时间 = 3974 毫秒。                         CPU 时间 = 1531 毫秒,占用时间 = 1964 毫秒。
 CPU 时间 = 2844 毫秒,占用时间 = 3961 毫秒。                         CPU 时间 = 1500 毫秒,占用时间 = 1959 毫秒。
 CPU平均  2937.3           占用时间平均  3992.6                             CPU平均  1510.3            占用时间平均1993
select count(1) from test                                                             select count(1) from test  where id <=8000000    
  CPU 时间 = 2906 毫秒,占用时间 = 4005 毫秒。                        CPU 时间 = 1422 毫秒,占用时间 = 1976 毫秒。
  CPU 时间 = 3015 毫秒,占用时间 = 4030 毫秒。                        CPU 时间 = 1344 毫秒,占用时间 = 1963 毫秒。 
  CPU 时间 = 2843 毫秒,占用时间 = 4065 毫秒。                        CPU 时间 = 1390 毫秒,占用时间 = 2052 毫秒。
  CPU平均  2921.3           占用时间平均 4033.3                              CPU平均1385.3            占用时间平均1997

由此可见 在主键上有聚集索引的情况下 如果做全表统计 
                   count(*)  count(id)  count(1)
CPU耗时       中            高              低
占用耗时       低             高             中
    在全表统计的时候为了获取相应速度count(*) 是第一选择,但如果系统瓶颈为CPU 那么应该选择count(1)
 在主键上有聚集索引的情况下 如果表记录上有限制条件
                   count(*)  count(id)  count(1)
CPU耗时       高             中              低
占用耗时       低             高              中
 在带限制条件的统计记录数时,count(1)为首选 总耗时略低于count(*) 但cpu耗时远低于count(*)