7

我开始用 PHP 开发一个 web 应用程序,我希望它会变得非常流行,让我变得有名和富有。:-)

如果到了那个时候,我决定是使用 SimpleXML 将 API 的数据解析为 XML 还是使用 json_decode 可能会对应用程序的可扩展性产生影响。

有谁知道这些方法中哪一种对服务器更有效?

更新:我进行了初步测试,看看哪种方法性能更高。执行起来似乎json_decodesimplexml_load_string. 这并不是非常确定的,因为它不会测试诸如并发进程的可伸缩性之类的东西。我的结论是,我将暂时使用 SimpleXML,因为它支持 XPath 表达式。

<?php

$xml  = file_get_contents('sample.xml');
$json = file_get_contents('sample.js');

$iters = 1000;

// simplexml_load_string
$start_xml = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
    $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
}
$end_xml = microtime(true);

// json_decode
$start_json = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
    $obj = json_decode($json);
}
$end_json = microtime(true);

?>
<pre>XML elapsed: <?=sprintf('%.4f', ($end_xml - $start_xml))?></pre>
<pre>JSON elapsed: <?=sprintf('%.4f', ($end_json - $start_json))?></pre>

结果:

XML elapsed: 9.9836
JSON elapsed: 8.3606
4

3 回答 3

10

作为“更轻”的格式,我希望 JSON 对服务器的压力会稍微小一些,但我怀疑这将是您发现自己处理的最大性能问题,因为您的网站越来越受欢迎。使用您更喜欢的格式。

Alternatively, if you know how you'll be structuring your data, you could try making an XML-formatted version and a JSON-formatted version and just run it against your setup a few hundred thousand times to see if it makes a noticeable difference.

于 2008-10-17T23:13:44.843 回答
3

There's only one way to determine which is going to be easier on your server in your application with your data.

Test it!

I'd generate some data that looks similar to what you'll be translating and use one of the unit testing frameworks to decode it a few thousand times using each of SimpleXML and json_decode, enough to get meaningful results. And then you can tell us what worked.

Sorry this isn't exactly the sort of answer you were looking for, but in reality, it's the only right way to do it. Good luck!

于 2008-10-18T01:11:59.537 回答
3

Not really an answer to the question, but you could just wait until you have lots of users hitting your system. You may be surprised where your bottlenecks actually lie:

http://gettingreal.37signals.com/ch04_Scale_Later.php

于 2008-10-19T13:00:11.427 回答