多次调用 time() 不好?

发布于 2024-11-24 12:02:41 字数 281 浏览 1 评论 0原文

我刚刚浏览了一些代码,想知道在页面上多次调用 time() 是否不好?

是的,我知道重复调用会起作用,但是速度会有很大差异吗?

Option #1: Call time() whenever you need the current Unix timestamp.

Option #2: Set a variable $timestamp = time(); and call the variable whenever the time is needed.

I was just going through some code and was wondering if it is bad to call time() multiple times on a page?

Yes, I know that it will work when called repeatedly, but will there be a big speed difference?

Option #1: Call time() whenever you need the current Unix timestamp.

Option #2: Set a variable $timestamp = time(); and call the variable whenever the time is needed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

后知后觉 2024-12-01 12:02:41

我希望 time() 相当便宜,但如果您在同一页面上多次调用它,您可能会遇到一些意想不到的不一致。例如,假设您调用它两次,一次显示日期,一次显示时间。如果两次调用之间的日期发生变化,您最终可能会显示前一天的午夜或第二天的 23:59:59(取决于调用的顺序)。

我通常希望整个页面被视为在单个瞬间呈现,在任何显示时间方面 - 因此调用它一次,并在多个地方使用该单个值。

I'd expect time() to be reasonably cheap, but if you call it multiple times on the same page you could get some unexpected inconsistencies. For example, suppose you call it twice, once to display the date and once to display the time. If the date changes between the two calls, you could end up showing midnight of the previous day, or 23:59:59 of the next day (depending on the order of the calls).

I would normally expect the whole page to be treated as being rendered in a single instant, in terms of any times displayed - so call it once, and use that single value in multiple places.

海之角 2024-12-01 12:02:41

这取决于具体情况。有些脚本运行时间超过几秒钟,有些脚本可能运行几个小时。然后将需要 time() 的新值。

如果时间差异短于 php 代码执行所需的时间不会导致任何问题,那么您不妨使用选项 #2,因为它稍微更快。但是,除非您大量调用 time(),否则速度差异可以忽略不计。

That depends on the situation. Some scripts run for more than a few seconds, some could run for hours. Then the new value of time() would be wanted.

If a difference in time that is shorter than the time it takes for your php code to execute won't cause any problems then you might as well use Option #2 since it is slightly faster. But, the speed difference is negligible unless you make tons of calls to time().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文