2013-01-25 11:49
浏览 66


I was just wondering which is considered to be more efficient in PHP.

I need to loop through MySQL results and output it to a file using a specific format, I am interested to know whether it's more efficient to create a huge string (I'm going to be going through over 100,000 rows) and write the string to a file, or write (append) what I want to add to the file using fwrite, as I'm going through the results?

From the outset, I believe using a very long string will be more efficient than keep writing to a file but I am wondering whether PHP is going to have any issues with processing a very long string?


图片转代码服务由CSDN问答提供 功能建议


我需要循环MySQL结果并使用特定格式将其输出到文件,我很想知道创建一个巨大的字符串是否更有效(我将要经历超过100,000行)并写入字符串 到一个文件,或者使用fwrite写入(追加)我要添加到文件中的内容,因为我正在查看结果?

从一开始,我相信使用一个非常长的字符串将比继续写入文件更有效但我想知道PHP是否会处理一个很长的字符串有任何问题 ?


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

2条回答 默认 最新

  • dongshanji3102 2013-01-25 11:54

    PHP wont have an issue with creating a very long string, it will however use a lot of memory. As long as you have enough memory available then this won't be an issue. Reading and writing from memory is much faster than writing to disk so going down the memory route could be an option although with 100,000 rows, you could split it up and get the best of both worlds.

    What I mean by this is every 10,000 rows append your string into the file and then empty the string, this way, you'll only be writing to file 10 times and storing a smaller amount of data in memory.

    打赏 评论
  • donglao6169 2013-01-25 11:53

    If you create a large string, try to collect all values into an array and join it together before writing. Strings are immutable, if you just append values to a String, this will lead to bad performance.

    Best solution would be to collect for example 1000 results, write this part to a file, collet another 1000 results and so on.

    打赏 评论

相关推荐 更多相似问题