Page 1 of 1
Reusing variables?
Posted: Fri Sep 26, 2003 6:39 pm
by Cruzado_Mainfrm
Is it ok, when u have a few queries in a single php page to reuse the same variable for the string of the query?
ex.:
Code: Select all
<?php
$query = "SELECT 4 XOR 3";
/* use the query string in a db query */
$query = "SELECT * FROM fruits";
/* use the query string in a db query */
?>
it's not a matter of forgetting what $query it was because before every db query execution there's a correspondant new or overwritten $query variable
Posted: Fri Sep 26, 2003 7:07 pm
by volka
no problem here.
The functions do not care about the source of a string, they simply take its value and use it (usually)
Posted: Fri Sep 26, 2003 7:12 pm
by Cruzado_Mainfrm
yes but i mean like in coding standards

Posted: Fri Sep 26, 2003 8:58 pm
by Stoneguard
back when variables and the strings the pointed to had to be allocated, it was better to reuse variable names. I still constantly reuse the same name (in my case I use $sql for a SQL query) because I can see each instance where it is initialized and can easily search for all my SQL (selects, insert, deletes, etc) by looking for my variable name.
If you were to actually make each variable a unique name, then you would in essence be allocating many block of memory to hold strings that get used once.
Code: Select all
<?php
// This uses slightly less memory
$sql = "select * from This";
query($sql);
$sql = "Select * from TheOther";
query($sql);
// This uses more memory
$sql1 = "select * from This";
query($sql1);
$sql2 = "Select * from TheOther";
query($sql2);
?>
But that's jsut my 2cents

Posted: Fri Sep 26, 2003 9:12 pm
by Cruzado_Mainfrm
i think the same too, it's like buying a box, then filling it, then after using it leave it there making space and then buy another box just to fill it again with something else, not using the first box and not discarding everything that was inside in it before...
Posted: Sat Sep 27, 2003 7:20 am
by JAM
Very interesting topic for benchmarking.
As Stoneguard mention, the server doesn't need to remember the different value when re-using a variable.
Personally I use different, but that is just to ease up on the readability and so on... Mileage may vary.
Posted: Sat Sep 27, 2003 8:46 am
by Cruzado_Mainfrm
i'll run a test to see which is faster, reusing variables or creating new ones
Posted: Sat Sep 27, 2003 10:42 am
by volka
since heap allocation has a worst-case complexity of O(log N) you have to grab a lot of memory to notice noteworthy changes. Probably more than the common single php-script does.
What's the memory limit set in your php.ini? What's the total amount of phsical memory your computer has and how much swapping is involved? PHP caches a lot and also note the guaranteed resolution of the timer you're going to use.
After all as long as
Moore's law holds I pay only little attention to anything that is measured in splitseconds and has a complexity less than polynominal
