duanjie1339 2014-07-24 17:14
浏览 64

在PHP中将字符数组写入文件的最快方法是什么?

Say I have an array $arr and I want to write its contents to a file $handle. What's the fastest/most efficient way to do this in PHP(5)?

Some different options:

Convert the array to a string using implode:

$string = implode($arr);
fwrite($handle, $string);

Write it to the file char by char (seems like it would be slower to me):

foreach($arr as $char) {
    fwrite($handle, $char);
}

Concatenate using the . operator and then write:

$string = '';
foreach($arr as $char) {
    $string .= $char;
}
fwrite($handle, $string);

The third seems like it would be slowest to me, as I'm guessing that fwrite and implode are written in C... but then again with JIT-compiling these days maybe it's optimizing the concatenations with no function call overhead.

Which of these -- or some other way -- is the fastest and why?

  • 写回答

1条回答 默认 最新

  • doumiang2297 2014-07-24 17:24
    关注

    Not sure about fastest/most efficient; but this opens the file, writes imploded data to the file and closes the file in one function:

    file_put_contents('/path/to/file.txt', $arr);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)