Amar
Amar

Reputation: 12010

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?

Upvotes: 7

Views: 7218

Answers (2)

gion_13
gion_13

Reputation: 41533

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 milliseconds faster but n seconds harder to read and maintain.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074385

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.

Upvotes: 7

Related Questions