Why use unset ? Does it optimize code ?

Discussion in 'PHP' started by domainsurfer, Jul 29, 2008.

  1. #1
    I have alot of variables in my script, should i use unset() to reset them after their use is finished ?

    if i have 20 unset() calls, doesnt this introduce unnecessary function call overhead ? Is the overhead lesser than the memory required to store those vars ?

    Which is better ? using unset() or keeping the vars as is ?
     
    domainsurfer, Jul 29, 2008 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    That depends on how much data these variables contain. Can you be more specific about that?

    And you don't need to call unset() for each variable, you can do:
    
    unset($foo, $bar, $lala, $some, $thing);
    
    PHP:
     
    nico_swd, Jul 29, 2008 IP
  3. domainsurfer

    domainsurfer Well-Known Member

    Messages:
    922
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    110
    #3
    some are mysql result sets, some are int vars.
     
    domainsurfer, Jul 29, 2008 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    I wouldn't bother unsetting them, in this case. The int variables will hold just a few bytes, and the MySQL results, well depends on what you've fetched previously. If it's a lot of data (binary images, etc...), then I'd probably unset them. But personally, I've only used unset() in a very few occasions.
     
    nico_swd, Jul 29, 2008 IP
  5. domainsurfer

    domainsurfer Well-Known Member

    Messages:
    922
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    110
    #5
    So its useless unsetting vars at the last line of the PHP script ?
     
    domainsurfer, Jul 29, 2008 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    At the last line, yes... PHP will automatically destroy them at the end of the execution of the script anyway. If you want to call it at all, do it right after the variable becomes useless to you.

    Also regarding this:
    unset() is a language construct, and not a function, and therefore much faster than a function.
     
    nico_swd, Jul 29, 2008 IP
  7. domainsurfer

    domainsurfer Well-Known Member

    Messages:
    922
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    110
    #7
    Thanks a lot for your help.
     
    domainsurfer, Jul 29, 2008 IP
  8. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #8
    I use unset when I am scarping stuff.

    Peace,
     
    Barti1987, Jul 29, 2008 IP