Reputation: 18595
I have a form with several fields that will be a fairly active. With that said there is a validation piece.
A user POST's and the values are stored in $_SESSION variables.
On fail, the $_SESSION variables are cleared that are incorrect. I do this because the form echo's back the previous values that are still correct, out of convience to the user.
Which is faster:
$_SESSION['variable']="";
PRO-->Less operations for each form POST
CON-->Server stores more $_SESSION variables at any given point.
unset($_SESSION['variable']);
PRO-->More operations for each form POST
CON-->Server stores less $_SESSION variables at any given point.
Thoughts?
Upvotes: 3
Views: 388
Reputation: 181
I'm not sure what you mean by "less operations for each form post" by setting the session var to an empty string. This is just a hip shot, but I'm guessing you're doing something like this ...
foreach( $_POST as $k => $v ) {
if( $v == 'correct value' ) {
$_SESSION[$k] = $v;
} else {
if( isset($_SESSION[$k] ) unset($_SESSION[$k] );
}
If not, then you probably ought to be. This way the only session variables that are ever set (thus using up resources) are going to be ones that are valid answers, and on the off chance that they're resubmitting a form and got a previously correct answer wrong it'll dump it. Then later on you can just do another foreach to dump out the session vars for the user's perusal.
Just as a common rule of thumb, unsetting a variable is preferable to setting it to "", as it removes it from memory, using less resources. The nanosecond or so required to re-set it, if required, is negligible unless you're talking about hundreds of thousands of requests per minute, and it doesn't sound like you are.
As for if it's absolutely critical? Meh. The company I work for has session variables that are literally pages long when I do a var_dump. 1000 plus instances of objects at the least, and our servers take millions of unique hits a month, so unless you're talking about more than that, I doubt it will ever really make that much of a noticeable difference to anyone.
Upvotes: 2
Reputation: 491
I agree with Alex. Yes you have to reinitialize the SESSION variable but depending on how the php interpreter is written they probably pre-allocate memory so that memory initialization is really fast making it just as fast as resetting the string in the first place. If anything I would just do it for the clarity.
Upvotes: 1
Reputation: 160973
Use unset($_SESSION['variable']);
to complete clear it completely.
By the way, if you do not redirect the page, you don't need to store the user input in the session.
Upvotes: 1
Reputation: 490657
You should unset()
as setting it to an empty string means the session variable still exists and is pointing to a location in memory.
You shouldn't worry at this stage which is faster, just think of what best communicates your code's intentions.
Upvotes: 4