dongyu5104
2019-03-07 11:29
浏览 61
已采纳

PHP会话变量请求时间

I was wondering wether it makes a difference in speed to save PHP SESSION Variables at the top of a script as Variables or just use the SESSION Variables through the entire script. e.g.

$_SESSION['bar'];

...

<p><?php echo $_SESSION['bar'] ?></p>
<p><?php echo $_SESSION['bar'][0] ?></p>

Or as explained above: Save the SESSION Variable first and then access that variable instead.

$bar = $_SESSION['bar'];

...

<p><?php echo $bar ?></p>
<p><?php echo $bar[0] ?></p>

Does it make any difference? Is PHP Requesting the SESSION Variables every single time from the server again?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanpie2414 2019-03-07 11:37
    已采纳

    Unless you do these session read/write operations millions of times (e.g. in a loop) you shouldn't be concerned with such micro optimizations. Even if you do them like that, I still think that PHP writes to session whenever that session is closed (not 100% sure about this last one).

    Remember that premature optimization is the root of all evil. :)

    On a more serious note:

    • It's always recommended to move code that's used more than once into a variable or a helper function (DRY principle)
    • By creating a helper function or a "wrapper" class for accessing low level services like Sessions, your code becomes "future proof" and not bound to an implementation. If in the future you decide to replace the storage engine from Session to, e.g, Cookies or Redis, you just change the helper class and the rest of the code keeps working. In other words, try to practice the Orthogonality principle.
    打赏 评论

相关推荐 更多相似问题