Antonis Antoniadis
Antonis Antoniadis

Reputation: 21

$_SERVER['DOCUMENT_ROOT'] vs $path = $_SERVER['DOCUMENT_ROOT']

Is there a difference in performance in these two different ways of including an external script?

Without using a variable:

include $_SERVER['DOCUMENT_ROOT'].'/class/conf.php';
include $_SERVER['DOCUMENT_ROOT'].'/class/Db.php';
include $_SERVER['DOCUMENT_ROOT'].'/class/Posts.php';

Using a variable:

$path = $_SERVER['DOCUMENT_ROOT'];
include $path.'/class/conf.php';
include $path.'/class/Db.php';
include $path.'/class/Posts.php';

I avoid variables the more i can for memory purposes but i dont know if this is a good practice for performance or not.

Upvotes: 1

Views: 1382

Answers (3)

Roseann Solano
Roseann Solano

Reputation: 768

If your class folder is located in the same place where you declare the inclusions.

$path = dirname(__FILE__).'/class/';

Then autoload your class from that folder.

function my_autoloader($class) {
    include $path . $class . '.php';
}

spl_autoload_register('my_autoloader');

Upvotes: 0

ComFreek
ComFreek

Reputation: 29444

I avoid variables the more i can for memory purposes but i dont know if this is a good practice for performance or not.

This is definitely not good practice. One variable is actually nothing for current processors.

Go for readability and maintainability!

In addition, a variable adds a layer of indirection, i.e. you can simply modify $path if you want to change your paths. Modifying $_SERVER['DOCUMENT_ROOT'] is not a good idea.

I would also advise you to create a constant instead of a variable:

define('CLASS_DIR', 'your value');

Upvotes: 4

Andy Lester
Andy Lester

Reputation: 93805

I avoid variables the more i can for memory purposes

This is what's called "premature optimization". Unless you know specifically that you have a memory problem, and that your assigning of a string that is maybe a few dozen characters long to it is adding to your memory problems, then don't try to save space.

Is there a difference in performance

Same goes for worrying about "performance". The amount of time difference between the two approaches is so small as to be meaningless, and certainly imperceptible, especially when it is only done once per script. Also, the amount of time different between the two ways of creating the string is insignificant compared to the time that it takes to hit the disk to load the PHP and parse it.

Far better to concern yourself with the DRY principle: Don't Repeat Yourself. DRY helps you prevent problems like this:

include $_SERVER['DOCUMENT_ROOT'].'/class/conf.php';
include $_SERVER['DOCUMEMT_ROOT'].'/class/Db.php';
include $_SERVER['DOCUMENT_ROOT'].'/class/Posts.php';

"None of my database functions work! What's wrong?"

Upvotes: 7

Related Questions