Page 1 of 1

Tip: Dont assign everything to variables

Posted: Tue Jul 13, 2004 10:05 am
by kettle_drum
Ive been seeing a lot of this recently so i thought i would post about it.....storing things in variables.

You should only store things in variables if your going to use them more than once, otherwise you are just wasting RAM by holding data in a variable that you will never use again. It may not seem like a big deal if you only coding small scripts, but you should really get into the habit of making your scripts lean and fast.

Bad Pratice:

Code: Select all

$time = time();
$sql = "INSERT INTO table (time) VALUES ('$time')";
mysql_query($sql);
This is a typical script that you see all over the place, and there is NO need to store values in variables before you call functions - it just wastes system resources and when you start to code large scripts and time-critical scripts they will be slower.

Solution:

Code: Select all

mysql_query("INSERT INTO table (time) VALUES ('".time()."')");
It does exactly the same thing except it doesnt store any variables in order to waste RAM making yor code cleaner and use less system resources.

Just my 2 cents there.

Any other views on the matter? Or other pratices that people should use? Look forward to hearing them.

Posted: Tue Jul 13, 2004 12:14 pm
by hawleyjr
Check out references also...

Posted: Tue Jul 13, 2004 2:53 pm
by redmonkey
When it comes to system resources, you can free up alot of memory by freeing SQL results when you have finished with them (something I see very little evidence of in the code snippets posted in these forums). You could also consider using mysql_unbuffered_query (assuming of course you are using MySQL) which in many cases is sufficent for your SQL queries.

In terms of general bad practice....

Code: Select all

for ($i = 0; $i < count($somearray); $i++)
That is quite possibly the most annoying piece of code I see, a better approach I feel is.....

Code: Select all

for ($i = 0, $limit = count($somearray); $i < $limit; $i++)
People using ereg_replace and preg_replace when a simple str_replace will do is another one that crops up from time to time.

Posted: Tue Jul 13, 2004 3:20 pm
by hawleyjr
redmonkey wrote:When it comes to system resources, you can free up alot of memory by freeing SQL results when you have finished with them
~Redmonkey Can you expand on this?

Posted: Tue Jul 13, 2004 3:38 pm
by redmonkey
hawleyjr wrote:~Redmonkey Can you expand on this?
When you query a database e.g.....

Code: Select all

SELECT * FROM somedatabasetable;
The result set is held in system memory to allow quick access when working with the result set e.g. using fetch_array, fetch_row, data_seek etc..

This result set is automatically cleared from the memory when the script terminates but, if you have alot of queries producing large result sets within the script and your server is being hit quite hard by multiple requests then it doesn't take too long for your system memory to be eaten up especially if you are on a heavily loaded virtual hosting server.

If memory is a concern then you should look at issuing a free_result command to the database (mysql_free_result() if using MySQL)

You can also use mysql_unbuffered_query() if you intend to use the results immediately and have no need for them to be stored in memory.

In most cases, it is not nessecary to free up SQL results but it is good practice to clean up after you as it will help script and general system performance if you free resources as soon as they are no longer required.

Posted: Tue Jul 13, 2004 3:50 pm
by hawleyjr
Thanks for the explanation. That makes a lot of sense especially if you are using: mysql_fetch_array()

Code: Select all

<?php
$result = mysql_query('SELECT id,co_name,main_phone,default_pass,dttm_added from TABLENAME'); 
      while($row = mysql_fetch_array($result)) 
      { 
      	echo '<PRE>'; print_r($row); echo '</PRE>';

      }

/*
WILL PRINT:

Array
(
    [0] => 28
    [id] => 28
    [1] => Test Name
    [co_name] => Test Name
    [2] => 800-555-1234
    [main_phone] => 800-555-1234
    [3] => hawley@hawleyjr.com
    [main_email] => hawley@hawleyjr.com
    [4] => testpass
    [default_pass] => testpass
    [5] => 2004-07-13 15:43:03
    [dttm_added] => 2004-07-13 15:43:03
    [6] => 2005-07-10
)

//AN ALTERNATIVE WOULD BE USING mysql_fetch_row()
//THAT WOULD RETURN:

Array
(
    [0] => 28
    [1] => Test Name
    [2] => 800-555-1234
    [3] => hawley@hawleyjr.com
    [4] => testpass
    [5] => 2004-07-13 15:43:03
    [6] => 2005-07-10
)
*/
?>

feyd | fixed the syntax ;)

Posted: Tue Jul 13, 2004 5:37 pm
by redmonkey
I haven't looked at it too closely so I'm unsure as to when exactly the result set is thrown out to memory, but, presumably it would be when you execute the query.

If that is correct, then it should not matter in terms of result set memory consumption as to which method you use to retrieve the results as I would think that the resul set in memory holds information about the column names regardless.

Your approach of using fetch_row instead of fetch_array would only conserve memory usage within the PHP script but would not affect memory usage/storage of the MySQL server. You could also use mysql_fetch_array(resource_handle, MYSQL_NUM) if you only wanted numerical indicies returned, or (mysql_fetch_array(resource_handle, MYSQL_ASSOC) or mysql_fetch_assoc(resource_handle)) if you require results returned within an associative array.

Posted: Tue Jul 13, 2004 5:56 pm
by McGruff
Actually the garbage collector will deal with obsolete vars / query resources etc as soon as the script is done with them. You are not gaining anything by not declaring a var. In fact, at times you are losing readability.

A long string - maybe a complex regex expression or sql query - might best be declared as a var, in stages over several lines using ".=". This can keep lines shorter and code neater - and therefore easier to read. Very dense statements should be broken down into simple elements. It's much easier to read and debug that way.

At other times it's maybe clearer to use $_POST['foo'] rather than $var = $_POST['foo'] simply because the former reminds you where the item came from.

Either way, I'd say the issue is what is easier to read - don't worry about memory.