问题
I need to create about 10k elements when a user visit my site, its sort of a big tree like <ul>
and <li>
.
The process of creating the HTML currently takes about 15 seconds, i create the HTML in an array then json_encode and echo it.
i am trying to shorten the process. my question is:
would it be faster to use php's DOM class to create the elements.
or just create the HTML and echo it?
回答1:
15 seconds to create and json_encode 10K elements .. this can't be right. The bottle neck is undoubtedly not PHP here. Where is that data coming from, a database ? In a single query or embedded queries in a loop ? Can the data be cached ? If so, do so.
You need to properly benchmark before optimizing, what you're trying to do now is trim milliseconds off an operation that takes 15 seconds.
回答2:
It looks like it is simple DOM hierarchy; just echo it!
回答3:
(rather too much here to fit in a comment - I don't think the question can or should be answered in it's current form)
Would it be so hard to find out for yourself?
Why do you create your data as a json data structure?
Surely you don't then convert it back to HTML on PHP?
Why not just write PHP?
Have you profiled your code to verify if the slow bit is generating the output rather than fetching the input?
Who is going to read 10k bullet points?
You've not shown us any code - and I don't know why or how you are using JSON. But using intermediate data structures (DOM or JSON) will be significantly slower than writing directly to the output buffer.
来源:https://stackoverflow.com/questions/17087086/creating-a-lot-of-dom-elements-which-method-is-faster-echoing-the-html-or-usin