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 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题