Hello there!
I was wondering the other day about having a session variable and copying it to a normal variable and using it in my scripts, and if its better to just use the session directly...
Here is an example of what i mean...
<?
session_start();
if(!isset($_SESSION["var"]))
{$_SESSION["variable"] = 1;}
$var = $_SESSION["var"];
// Use var in other pages
include_once("page_to_use_var.php");
$_SESSION["var"] = $var;
?>
I always liked to copy my session data i would be using to a temporary variable to use on pages then when im done update the session data with the data in the variable. However ive got a fairly large project which has a few objects which are cached from a database and stored in the session for persistance to stop constant database updates. It runs well but now im thinking that maybe its going to be taking up more memory and slowing it down when im doing things this way. So is it worth just using the session directly instead of copying a temporary variable... here is an example of what i mean:
<?
class SuperClass
{
var $arrData;
function SuperClass()
{
$this->arrData = array();
for($i=0;$i<100;$i++)
{$this->arrData[$i] = rand(0,10000);}
}
function getData($index)
{return $this->arrData[$index];}
function setData($index, $data)
{$this->arrData[$index] = $data;}
}
session_start();
if(!isset($_SESSION["SuperClass"]))
{$_SESSION["SuperClass"] = new SuperClass();}
$oSuperClass = $_SESSION["SuperClass"];
include_once("page_to_use_super_class.php");
$_SESSION["SuperClass"] = $oSuperClass;
?>
The above method would in my mind waste memory as you are copying the array then using it in the pages then putting the altered object back into the session. It would be fine for small variables like an int or so but with larger objects would it be faster to not bothering to copy out the session data and just use the raw session as the object... heres what i mean 😃
// One Way
$_SESSION["SuperClass"]->setData(1,100);
// Other Way
$oClass = $_SESSION["SuperClass"];
$oClass->setData(1,100);
$_SESSION["SuperClass"] = $oClass;
Anyone got any semi factual evidence to say which would be faster and why you should/shouldnt use the session directly with objects?