在手册上看到的,原文地址为:http://cn.php.net/manual/en/function.spl-autoload.php
很吃惊,原来,在默认情况下,spl_autoload的效率并不高?
我没有测试,原文测试的时间在07年,不知道现在的效率怎么样了。以后有空的时候测试一下。。。
以下是原文:
Note that, the orders of file extensions is important for performance. You should make the priority of your favourite file extension higest or use only one extension for your class files. Check out this example:
Some class files:
ClassA.php
PHP代码
- <?php class ClassA { var $val = 'Hello from class "ClassA"'; } ?>
ClassB.php
PHP代码
- <?php class ClassB { var $val = 'Hello from class "ClassB"'; } ?>
ClassC.php
PHP代码
- <?php class ClassC { var $val = 'Hello from class "ClassC"'; } ?>
ClassD.php
PHP代码
- <?php class ClassD { var $val = 'Hello from class "ClassD"'; } ?>
ClassE.php
PHP代码
- <?php class ClassE { var $val = 'Hello from class "ClassE"'; } ?>
1. Simple:
PHP代码
- <?php
-
- for($n=65; $n<70; $n++) {
- $className = 'Class'.chr($n);
- spl_autoload($className);
- $ins = new $className;
- echo $ins->val.'<br>';
- }
-
- ?>
2. Change priority:
PHP代码
- <?php
- spl_autoload_extensions('.php,.inc');
-
- for($n=65; $n<70; $n++) {
- $className = 'Class'.chr($n);
- spl_autoload($className);
- $ins = new $className;
- echo $ins->val.'<br>';
- }
-
- ?>
Or you can use this simple function that runs a bit faster for the extensions with lower priority :)
PHP代码
- <?php
- function my_autoload($className, $extList='.inc,.php') {
- $ext = explode(',',$extList);
- foreach($ext as $x) {
- $fname = $className.$x;
- if(@file_exists($fname)) {
- require_once($fname);
- return true;
- }
- }
- return false;
- }
-
- for($n=65; $n<70; $n++) {
- $className = 'Class'.chr($n);
- my_autoload($className);
- $ins = new $className;
- echo $ins->val.'<br>';
- }
-
- ?>
---
Safak Ozpinar - Istanbul University, Computer Engineering