SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Community Advisor silver trophybronze trophy
    dresden_phoenix's Avatar
    Join Date
    Jun 2008
    Location
    Madison, WI
    Posts
    2,732
    Mentioned
    31 Post(s)
    Tagged
    0 Thread(s)

    Conditionals and fuctions.

    if you have a COMPOUND conditional statement ( such as "IF") that based on the return value of a function... FOR EXAMPLE:
    if ( foo()>0 && foo()%2==1 && (foo()==7 || foo()!=2){...} // the value returned by foo() is not used anywhere else is the function called multiple times or is the value cached by PHP?

    I guess what I am asking is ... tho it would involve an ADDITIONAL LINE of code and memory allocation , in situations as described is better to store the value returned foo() in a variable or are there NO significant gains ( other than organizational) ?

  2. #2
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    PHP won't cache it.

    Performance wise, I doubt anyone here knows the exact difference between say... 4 function calls vs 1 function call + a variable. However function calls do have a slight overhead, but so does initializing and assigning a value to a variable. Obviously it would depend heavily on what the function is doing as well.

    Generally this performance issue is apparent in loops, like for loops where you might do something like for ($i=0; $i < foo(); $i++) and it'll be run thousands of times.

    However in your case of just a handful of times, I would personally say - use a variable, because from a maintenance perspective - it will be easier to modify. Performance wise it won't matter either way.

  3. #3
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Without knowing the steps function foo() does...can only guess if it would benefit being saved to a variable.
    PHP Code:
    if ( ( $bar foo() ) > && ( $bar ) == && ( $bar == || $bar != ) ) { ... } 
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •