Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting Delimited String vs JSON Parsing Efficiency in JavaScript

I need to retrieve a large amount of data (coordinates plus an extra value) via AJAX. The format of the data is:

-72.781;;6,-68.811;;8

Note two different delimiters are being used: ;; and ,.

Shall I just return a delimited string and use String.split() (twice) or is it better to return a JSON string and use JSON.parse() to unpack my data? What is the worst and the best from each method?

like image 861
Amar Avatar asked Mar 25 '13 13:03

Amar


People also ask

Is JSON parse fast?

parse is a slow way to create a copy of an object.

Is JSON difficult to parse?

Actually unless one is doing JavaScript, JSON is extremely difficult to parse correctly.

Is JSON Parsable JavaScript?

JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() , and the data becomes a JavaScript object.

Is parsing JSON safe?

Parsing JSON can be a dangerous procedure if the JSON text contains untrusted data. For example, if you parse untrusted JSON in a browser using the JavaScript “eval” function, and the untrusted JSON text itself contains JavaScript code, the code will execute during parse time.


2 Answers

Even if the data is really quite large, the odds of their being a performance difference noticeable in the real world are quite low (data transfer time will trump the decoding time). So barring a real-world performance problem, it's best to focus on what's best from a code clarity viewpoint.

If the data is homogenous (you deal with each coordinate largely the same way), then there's nothing wrong with the String#split approach.

If you need to refer to the coordinates individually in your code, there would be an argument for assigning them proper names, which would suggest using JSON. I tend to lean toward clarity, so I would probably lean toward JSON.

Another thing to consider is size on the wire. If you only need to support nice fat network connections, it probably doesn't matter, but because JSON keys are reiterated for each object, the size could be markedly larger. That might argue for compressed JSON.

like image 56
T.J. Crowder Avatar answered Sep 22 '22 17:09

T.J. Crowder


I've created a performance test that describes your issue.
Although it depends on the browser implementation, in many cases -as the results show- split would be much faster, because JSON.parse does a lot of other things in the background, but you would need the data served for easy parsing: in the test I've added a case where you use split (among replace) in order to parse an already formatted json array and, the result speaks for itself.

All in all, I wouldn't go with a script that's a few miliseconds faster but n seconds harder to read and maintain.

like image 37
gion_13 Avatar answered Sep 19 '22 17:09

gion_13