Search code examples
javascriptjsonperformancesplitstring-parsing

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?


Solution

  • 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.