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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试