数据库最重要是的为前台应用服务。 在众多决定应用性能的因素中, 如何快速有效从后台读取数据很大程度上地影响到最终效果。本文将对不同的数据往返(round-trip)读取进行比较和归纳总结。最后的结果非常出人意料。往往在时间紧迫的情况下,我们会本能地使用最简单的方法来完成任务,但是这种编译习惯会让我们的前台应用的性能大打折扣。
返回 15,000 条数据:这个测试会从一个表格里面读取15000条数据。我们通过用三种不同的编译方式来看如何提高数据库提取的效率。
以下这个脚本用来创建表格然后放入一百万条数据。因为我们需要足够多的数据来完成3个测试,每个测试读取新鲜的数据,所以创建了一百万条。我创建的这个列表每15000条数据一小组,这样确保了测试读取15000条数据的准确性。不会因为数据的不同,而影响测试的结果。
这个脚本稍作修改就可以放在MS SQL服务器上跑:
create table test000 (
intpk int primary key
,filler char (40)
)
declare @x,@y;
set @x = 1;
set @y = string(40,40,1);
while @x <= 5000 begin
insert into test000 (intpk,filler)
values ((@x-1)*200 +1, '@y' );
set @x = @x + 1;
end
select * into test000_temp from test000
declare @x;
set @x = 1;
while @x <= 199 begin
insert into test000 (intpk,filler)
select intpk+@x,filler from test000_temp;
set @x = @x + 1;
end
|
|
测试-:基本代码
最简单的代码就是通过一个直白的查询语句跑15000次往返。
# Make a database connection
$dbConn = pg_connect( "dbname=roundTrips user=postgres" );
# Program 1, Individual explicit fetches
$x1 = rand(0,199)*5000 + 1;
$x2 = $x1 + 14999;
echo "\nTest 1, using $x1 to $x2" ;
$timeBegin = microtime( true );
while ($x1++ <= $x2) {
$dbResult = pg_exec( "select * from test000 where intpk=$x1" );
$row = pg_fetch_array($dbResult);
}
$elapsed = microtime( true )-$timeBegin;
echo "\nTest 1, elapsed time: " .$elapsed;
echo "\n" ;
|
|