Skip to content

Instantly share code, notes, and snippets.

@ranacseruet
Created January 14, 2014 03:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ranacseruet/8412771 to your computer and use it in GitHub Desktop.
Save ranacseruet/8412771 to your computer and use it in GitHub Desktop.
Benchmark for arrayaccess vs object access for PHP classes
//test.class.php
<?php
class Test implements ArrayAccess
{
private $data = array();
public function __set($key, $value){
$this->data[$key] = $value;
}
public function __get($key){
return $this->data[$key];
}
public function offsetExists($offset) {
}
public function offsetGet($offset) {
return $this->__get($offset);
}
public function offsetSet($offset, $value) {
$this->__set($offset, $value);
}
public function offsetUnset($offset) {
}
}
//benchmark.php;
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include "test.class.php";
echo "array access style: ".time()."<br>";
for($i=0 ; $i < 900000; $i++)
{
$test = new Test();
$test["a"] = "test a";
$test["b"] = "test b";
$test["c"] = "test c";
$temp = $test["a"];
$temp = $test["b"];
$temp = $test["c"];
}
echo time()."<br>";
echo "function call style: ".time()."<br>";
for($i=0 ; $i < 900000; $i++)
{
$test = new Test();
$test->__set("a", "test a");
$test->__set("b", "test b");
$test->__set("c", "test c");
$temp = $test->__get("a");
$temp = $test->__get("b");
$temp = $test->__get("c");
}
echo time()."<br>";
echo "Objec property style: ".time()."<br>";
for($i=0 ; $i < 900000; $i++)
{
$test = new Test();
$test->a = "test a";
$test->b = "test b";
$test->c = "test c";
$temp = $test->a;
$temp = $test->b;
$temp = $test->c;
}
echo time()."<br>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment