I'm writing an API for retrieving data from a JDBC-connected Java Servlet via JSON. I've chosen to use JSON because we'll want to do sorts and other operations on the data in the browser, and we'll be accessing the data from across domains.
Since I'm essentially doing SQL queries in JavaScript, the data that comes back is tabular in nature. I started to write this so that you get back a list of column labels, then arrays of values, for example:
{
columns: [
given_name,
surname,
],
results: [
[
Joe,
Schmoe
],
[
Jane,
Doe
]
]
}
But as I start to write the JavaScript to deal with the returned data, I wonder if it might be better to just output the results with key/value pairs, such as:
{
results: [
{
given_name: Joe,
surname: Schmoe
},
{
given_name: Jane,
surname : Doe
}
]
}
If you're returning a lot of results, that's a lot of repeated text. But we're going to be transporting gzipped, so I'm not too concerned about bandwidth.
Basically, should I engineer this so that I'm accessing my data with
$.getJSON(query, function(data) {
var columns = data.columns;
var results = data.results;
$.each(results, function(key, row) {
console.log(row[columns.indexOf('surname')]);
});
});
or the much prettier
$.getJSON(query, function(data) {
var results = data.results;
$.each(results, function(key, row) {
console.log(row.surname);
});
});
?
Essentially, I want to know if the potential hit to performance justifies the much cleaner syntax of the latter option.
Follow up
I did implement it both ways and profile. Profiling was a great idea! The differences in performance were marginal. The differences in data transfer size were substantial, but with Gzip compression, the variance was down to 5-6% between both formats and between very large and very small data sets. So I'm going with the prettier implementation. For this particular application, I can expect all clients to support Gzip/Deflate, so the size doesn't matter, and the computational complexity on both the client and server is similar enough that it doesn't matter.
For anyone interested, here is my data with graphs!.