Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ::: Speed Test ::: $_SESSION ::: unset() vs. blank string

Tags:

php

session

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?

like image 265
Dan Kanze Avatar asked Mar 15 '26 06:03

Dan Kanze


2 Answers

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.

like image 64
alex Avatar answered Mar 17 '26 20:03

alex


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.

like image 41
CrimsonKissaki Avatar answered Mar 17 '26 19:03

CrimsonKissaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!