php數組性能小測


今天看到一個同事寫的php程序 突然想測試一下php的兩種數組定義方式的性能差別


簡單測試代碼如下:

1.使用array關鍵字

<?php
set_time_limit( 120 );
echo time();
for( $i = 0; $i < 10000000; ++$i )
{
	$arr = array( 'a' => 0,
			'b' => 1,
			'c' => 2,
			'd' => 3,
			'e' => 4,
			'f' => 5,
			'g' => 6,
			'h' => 7,
			'i' => 8,
			'j' => 9,
			'k' => 10,
			'l' => 11,
			'm' => 12,
			'n' => 13,
			'o' => 14,
			'p' => 15,
			'q' => 16,
			'r' => 17,
			's' => 18,
			't' => 19,
			'u' => 20,
			'v' => 21,
			'w' => 22,
			'x' => 23,
			'y' => 24,
			'z' => 25,
			'a1' => 0,
			'b1' => 1,
			'c1' => 2,
			'd1' => 3,
			'e1' => 4,
			'f1' => 5,
			'g1' => 6,
			'h1' => 7,
			'i1' => 8,
			'j1' => 9,
			'k1' => 10,
			'l1' => 11,
			'm1' => 12,
			'n1' => 13,
			'o1' => 14,
			'p1' => 15,
			'q1' => 16,
			'r1' => 17,
			's1' => 18,
			't1' => 19,
			'u1' => 20,
			'v1' => 21,
			'w1' => 22,
			'x1' => 23,
			'y1' => 24,
			'z1' => 25
	);
}

echo '<br>';
echo time();
exit();

執行時間:1398407484 - 1398407432 = 52s

2.不使用array關鍵字

<?php
set_time_limit( 120 );
echo time();
for( $i = 0; $i < 10000000; ++ $i )
{
	$arr2 ['a'] = 0;
	$arr2 ['b'] = 1;
	$arr2 ['c'] = 2;
	$arr2 ['d'] = 3;
	$arr2 ['e'] = 4;
	$arr2 ['f'] = 5;
	$arr2 ['g'] = 6;
	$arr2 ['h'] = 7;
	$arr2 ['i'] = 8;
	$arr2 ['j'] = 9;
	$arr2 ['k'] = 10;
	$arr2 ['l'] = 11;
	$arr2 ['m'] = 12;
	$arr2 ['n'] = 13;
	$arr2 ['o'] = 14;
	$arr2 ['p'] = 15;
	$arr2 ['q'] = 16;
	$arr2 ['r'] = 17;
	$arr2 ['s'] = 18;
	$arr2 ['t'] = 19;
	$arr2 ['u'] = 20;
	$arr2 ['v'] = 21;
	$arr2 ['w'] = 22;
	$arr2 ['x'] = 23;
	$arr2 ['y'] = 24;
	$arr2 ['z'] = 25;
	
	$arr2 ['a1'] = 0;
	$arr2 ['b2'] = 1;
	$arr2 ['c2'] = 2;
	$arr2 ['d2'] = 3;
	$arr2 ['e2'] = 4;
	$arr2 ['f2'] = 5;
	$arr2 ['g2'] = 6;
	$arr2 ['h2'] = 7;
	$arr2 ['i2'] = 8;
	$arr2 ['j2'] = 9;
	$arr2 ['k2'] = 10;
	$arr2 ['l2'] = 11;
	$arr2 ['m2'] = 12;
	$arr2 ['n2'] = 13;
	$arr2 ['o2'] = 14;
	$arr2 ['p2'] = 15;
	$arr2 ['q2'] = 16;
	$arr2 ['r2'] = 17;
	$arr2 ['s2'] = 18;
	$arr2 ['t2'] = 19;
	$arr2 ['u2'] = 20;
	$arr2 ['v2'] = 21;
	$arr2 ['w2'] = 22;
	$arr2 ['x2'] = 23;
	$arr2 ['y2'] = 24;
	$arr2 ['z2'] = 25;
}

echo '<br>';
echo time();
exit();

執行時間 1398407870 - 1398407832 = 38s


二者性能相關巨大

所以在定義數組時最好使用單行定義的方式盡管這可樣可以讓你多寫一些代碼 不過一些更高的性能還是不錯的 尤其是在訪問量大的網站上 尤其你又是C出身程序員


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com