dongyo1959 2011-08-05 04:24
浏览 66
已采纳

编写一个PHP脚本,在垂直行中生成数字1到10

I recently gave an interview at a company where they asked me the following question:

"If server/site optimization is most important, please write a PHP script that generates the numbers 1 through 10 in a vertical line - IE - 1, then a line break, then 2, then a line break, etc."

While I could write this program in so many ways I don't think any of them is better than others in terms of server load and performance. For example:

for ($i = 1; $i <= 10; $i++) {
    echo $i . '<br />';
}

So I have got 2 questions here:

  1. Can we really optimize this code for performance?
  2. If yes, how? If not, how to respond to this question?
  • 写回答

4条回答 默认 最新

  • dqsh30374 2011-08-05 14:54
    关注

    Because the server load is most important, I'd say the cheapest way is to deliver the minimum content to your users over the network with very little CPU load. Sending straight text will cause the lightest CPU load for similarly sized programs, so in this case, I'd go with a solution similar to Joey Adams's solution, though I'd remove 5 chars. Also, I've updated with Peter Taylor's suggestion of using the pre tag (48 chars - 40 over network):

    echo "<pre>1
    2
    3
    4
    5
    6
    7
    8
    9
    10</pre>";
    

    This is better in this case because the requirement is short. However, let's say we wanted to optimize 100 numbers and line breaks for the server. In that case, if you calculate it in PHP and send the full result over the internet, that would be 9 + 9*3 + 90*4 + 3 = 399 characters plus additional server overhead for the calculations if you did not hard-code it. Thus, instead of performing the logic within PHP and then sending the full result to the client, you could send a smaller script to the client that will build the content for you while at the same time reducing the load on your server. Here's an example bit of JavaScript/HTML you could build and send with PHP (136 chars - 128 over network):

    echo "<pre id=\"c\"><\pre><script type=\"text/javascript\">for(i=0;i++<100;){document.getElementById('c').innerHTML+=i+'
    ';}</script>";
    

    Here's a fiddle to see it in action.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器