The most obvious difference in speed was recursive traversal of dom elements in Javascript, which is always a lot faster than the same method implemented in Java.
Why is this the case? Why am I able to trav开发者_JAVA百科erse dom document much quicker than Java, especially when they share the identical method (recursion).
It's because browsers do not have interpreters for java. They interpret javascript. The DOM is a model that can be used anywhere, but it used mostly in the browser environment, and browsers have optimized DOM parsing over the years... for javascript.
The reason browsers have optimized DOM parsing is due to the fact that DOM parsing is a cornerstone of dynamic web development. Consider the normal way to make a page more dynamic:
1.) Listen for some events fired on the page.
2.) When those events are fired, modify some number of DOM objects,
e.g., by changing their visibility, geometry, or actually moving
them to other portions of the DOM.
The reason the DOM is important here is because it provides a specification for storing a document in browser memory so that an entire page doesn't have to be re-rendered by changes to small portions of the markup. And these DOM objects stored in browser memory are structured just like native javascript objects; therefore, it's easier to optimize for javascript against them.
And ever since dynamic web pages have become essential, browsers have been fighting each other tooth and nail to have the fastest custom javascript interpreter, and in a dynamic web environment, the main place where you're going to be able to see the most rewards for optimizing is DOM parsing.
I can't see the pressing need in a java environment to use a DOM, but it's absolutely essential in a browser environment. That is the most likely reason you have seen better optimizations in javascript for DOM parsing than java. More people have a vested interest in making it work in the browser. However, for clarification, I'm not sure of the exact technical reasons at the code level why it's actually faster.
I think the answer can be summarised with "Because that's the kind of access that the browser developers have put more effort into."
If, in an alternate universe, everybody used Java to provide rich interactivity on web pages and Javascript was only used for annoying scrolling banner bars, then you might very well be asking the opposite question. In such a universe, the browser vendors would have made DOM access from Java as fast as possible.
Your Java code is probaby using a general-purpose XML parser such as Xerces, with error correction taking place for the non-XML-compliant parts of HTML. Your Javascript is probably using a highly-optimized HTML-specific parser whose CPU-intensive portion is almost certainly implemented in native code.
精彩评论