views:

152

answers:

3

Which is faster,

  1. Using an XMLHTTP Get request and than using eval() for the reponsetext

  2. Using the JSONP technique for loading a script and then evaling the innerHtml of the script.

  3. Dynamically adding a script tag to the head of a document where the javascript object is being assigned to a variable?

My gut tells me this should be option 3, but I am not sure how eval compares with using a script tag. Any thoughts?

+1  A: 

It could vary based on browser and some other factors so I think if you really want the best performance you should do some tests and profile them. For one, eval() performance can vary tremendously depending on what you are eval()'ing

jarrett
A: 

You should just use the JSON2 library to parse json data, as using eval is unsafe (using eval results in a large number of potential site exploits), it's slow (especially in the newer jitting JS engines), and finally (and more importantly) the JSON object provided by the JSON2 library is becoming part of the ecma script (eg. javascript) standard, which means browsers are now implementing the json parsing (and stringification) natively resulting in vastly improved performance.

Happily if you use the JSON2 library it detects the existence of a native implementation of the JSON object and doesn't override it, so just arbitrarily using it will give you a safe implementation that will magically become faster as browser support improves.

olliej
A: 

I agree JSON2 library is probably the way to go for eval()'ing. But for transport, it looks like the JSONP mechanism is faster than XMLHTTPRequest per some analysis that John Resig has done.

http://ejohn.org/blog/native-json-support-is-required/

crink