数组上推荐引用的问题?
这是我不久前需要澄清的事情。在 PHP 5.3+ 中,我想问这是否可以提高非常大的数组结果的性能?你有办法让我证明这一点吗?
$synonyms = & MobyThesaurus::GetSynonyms("check");
请注意&符号(通过引用,而不是通过值)。
This is something I needed to clear up awhile back. In PHP 5.3+, I wanted to ask if this improves performance on a very large array result? And do you have a way I can demonstrate the proof?
$synonyms = & MobyThesaurus::GetSynonyms("check");
Note the ampersand (by reference, instead of by value).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PHP 在幕后使用写时复制。意思是,值仅在更改时才会被复制。在此之前,不会进行任何复制,而且
$synonyms
基本上只是充当参考。如果您仅从数组中读取,那么性能应该没有差异。一旦您写入数组,无论变量是否为引用,确实都会在功能上产生相当大的差异。除非您有意,否则请勿使用引用,否则可能会给您的应用程序带来奇怪的副作用。
幕后正在进行许多优化,不要指望能够用这样的“技巧”来优化它。 PHP 是一种错误的语言,因为它巧妙地运用了指针/引用技巧。 :-)
PHP uses copy-on-write behind the scenes. Meaning, values are only copied when they're altered. Until then there's no copying going on and
$synonyms
basically acts as a reference anyway. If you're only ever reading from the array, there should be no difference in performance.Once you are writing to the array, it does make quite a bit of difference in functionality whether the variable is a reference or not. Don't use references unless you mean to, or you may introduce funky side effects into your app.
There are a many optimizations going on behind the scenes, don't expect to be able to optimize it any more with such "tricks". PHP is the wrong language for being clever with pointer/reference acrobatics. :-)