Created
January 14, 2014 03:50
-
-
Save ranacseruet/8412771 to your computer and use it in GitHub Desktop.
Benchmark for arrayaccess vs object access for PHP classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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