I am using php 5.6 and I need a class to access an item at a certain position. After some profiling I found that simply getting data was dreadfully slow...
Using the following sample code...
class A{
protected $_x = [0,1,2,3,4,5,6,7,8,9];
public function at($pos){
if( $pos < 0 || $pos > count($this->_x )){
throw new Exception("out of range!");
}
return $this->_x[$pos];
}
}
$time_pre = microtime(true);
$a = new A();
for( $j = 0; $j < 1000; ++$j )
{
for( $i = 0; $i < 10; ++$i ){
$x = $a->at($i);
}
}
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
echo "Class={$exec_time}ms<br>";
$time_pre = microtime(true);
$a = [0,1,2,3,4,5,6,7,8,9];
for( $j = 0; $j < 1000; ++$j )
{
for( $i = 0; $i < 10; ++$i ){
$x = $a[$i];
}
}
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
echo "Array={$exec_time}ms<br>";
The output I got was
Class=0.51763796806335ms
Array=0.0022461414337158ms
Note that
- The class A() is created once only, I am just calling the function 'at()'
- The array is also only created once, I am just accessing it.
- If I remove the 'if( $pos < 0 | ...' check, the code is still over 200 times slower.
So my question is, why is the class so much slower than direct access to the function, effectively the at( ... ) function is just getting the value from the array.