Question

I am doing the finishing microoptimizations on my site and noticed that in many of my php files that are called via AJAX, I have a $_GET variable that is used many times in the php file:

<?php include 'connect.php';

$var = $_GET['x'];

$var1 = $var . "...";
$var2 = $var . $var;

$sql = mysqli_query($cxn, "SELECT user FROM login WHERE login_id = '$var'");

//etc.

At this point, my thinking is that if the code was rewritten as:

<?php include 'connect.php';

$var1 = $_GET['x'] . "...";
$var2 = $_GET['x'] . $_GET['x'];

$sql = mysqli_query($cxn, "SELECT user FROM login WHERE login_id =  
'".$_GET['x']."'");

//etc.

this, while equivalent in output to the first block of code, would actually be slower because the code must $_GET 'x' 4 SEPARATE times versus once in the first block of code. The first is faster because this copy of $_GET['x'] is accessed and processed more quickly. Similarly, I imagine this would also apply to php functions () and $_POST such as the following:

$unixtime = time();

while ($row = mysqli_fetch_assoc($sql)) {
$TimeVar = $unixtime; //Good....a copy of time() is used each time, so time is 
calculated only once   
}

vs:

while ($row = mysqli_fetch_assoc($sql)) {
$TimeVar = time(); //Bad....time() is recalculated for each iteration of the while loop
}

So, do $_GETs and $_POSTs get processed separately for each instance? Functions such as time()? Sorry for the beginner's level questions...hope it is OK :)

Was it helpful?

Solution

$_GET, $_POST, $_SERVER, $_SESSION, etc. are all global variables that are initialized once at the beginning of script processing. It doesn't matter if you access it once, or a million times, the time it takes to create the variable will be the same.

That said, assigning a given value to a variable might give you a bit of a performance difference. The array lookup of $_GET['x'], since it has to parse the string, go to the data structure, and pull it from there, might take a bit of time. However, assigning it to a variable might make the engine use more memory (I don't know if PHP does copy-on-write or not), and possibly do more swapping from cache to memory and back as it has to access a different variable.

That said, any differences would be on the order of tenths or hundredths of a millisecond to page load. Significantly less than you could possibly measure, and much less than the typical variation of a page load.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top