dos71253 2016-11-22 11:07
浏览 56
已采纳

为大查询响应优化内存资源

I have to perform a query that can generates a very big string in response (up to 1Gb), which is basically a big, big JSON array. Yes, pagination is in order but I'm stressing the concept in order to get you the idea. Symfony simply uses doctrine to get the response:

    $stmt = $this->getEntityManager()->getConnection()->prepare(self::Q_GET_NUM_TIMEBOX);

    $stmt->bindValue('t_end', $tEnd);
    $stmt->bindValue('t_granularity', $tGranularity);
    $stmt->bindValue('t_span', $varSelection->getStart());

    $stmt->execute();

    $resData = $stmt->fetchColumn(0);

and then I create a Response by setting the content I had in return from the execute.

    $res = new Response();
    $res->setStatusCode(200);
    $res->headers->set('Content-Type', 'application/json');
    $res->setContent($resData);

Keep in mind I oversimplified the code for the sake of clarity: I actually have a controller, a handler service performing the request and a Repository returning the query response.

Back straight to the problem: this implies that PHP must hold that big amount of data in memory and I was wondering if there was an lighter way to return the response in order to stress less PHP engine with big amount of data.

  • 写回答

1条回答 默认 最新

  • douzong5473 2016-11-22 11:49
    关注

    this implies that PHP must hold that big amount of data

    PHP is not required to keep in the memory a whole response body. Through output buffers and Symfony response streaming you can fetch result set row-by-row and send a data by chunks. Unfortunately I don't known well-tried solution for JSON stream encoding in PHP, but you can implement it manually (1, 2).

    Update (2017-02-27):

    Streaming JSON Encoder is a PHP library that provides a set of classes to help with encoding JSON in a streaming manner, i.e. allowing you to encode the JSON document bit by bit rather than encoding the whole document at once.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值