PHP 5: Performance Issue - Session Variable.
Posted on 2004-08-05
Using PHP 5 and smarty:
I have mapped my system out such that individual processes (such as registering users etc) are controlled by a control class (object). This control object has an associative array of variables which it stores and extracts from the session. Each time the page is loaded, the object constructor retrieves this array from the session. Data could be status, error messages etc. The controls basically handle all logic and load templates based on the status that is kept through the session. My question has to do with performance in extracting and updating this array from the session.
PHP 5's array model is unlike its object model. That is, if I have a large array, when copied, the array will be deep copied as well. Objects held in the array will obviously keep only a reference. But for my control variable array there are a collection of strings, objects etc.
If I do the following
$controlVarArray = $_SESSION['controlVarArray'];
// Lets say controlVarArray has a single object and an error message ("error").
$o = $controlVarArray['myObject'];
$mess = $controlVarArray['errorMessage']; // $mess = "error"
// If I then update the object, the reference changes and I don't have to worry about updating the session variable again.
// But if I change the error, it is not by reference so it doesn't change in the session
$controlVarArray['errorMessage'] = "newMessage";
If I output the session data now it will have the object with myNewName, but it will still have "error" as the errorMessage.
So there are a number of things I could do. Which one would you do and why would be ideal.
1. I could get a reference to the session variable. Something like $controlVarArray = &$_SESSION['controlVarArray'];
I am worried that I am getting the same performance hit as referencing the slow $_SESSION variable.
2. I could update the session variable explicitly each time. Something like $_SESSION['controlVarArray'] = $controlVarArray.
This is a little ugly in my definition, as it would require the update after each change (or status change).
3. I could wrap the array in an object and simply set and extract that reference. I am leaning towards this, however I am not sure if I am suffering from the same penalty as 1. I believe it would depend on how the object reference is stored. . .
I will reward people with any useful insight. . .
I apologize if this is worded unclearly. . .