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.
因为我基本上是在用JavaScript进行SQL查询,所以返回的数据本质上是表格式的.我开始写这篇文章,这样你可以得到一个列标签列表,然后是值数组,例如:
{
"columns": [
"given_name",
"surname",
],
"results": [
[
"Joe",
"Schmoe"
],
[
"Jane",
"Doe"
]
]
}
但是,当我开始编写JavaScript来处理返回的数据时,我想知道是否只输出带有键/值对的结果会更好,例如:
{
"results": [
{
"given_name": "Joe",
"surname": "Schmoe"
},
{
"given_name": "Jane",
"surname" : "Doe"
}
]
}
如果你返回了很多结果,那就是很多重复的文本.但是我们将要传输Gzip,所以我不太关心带宽.
基本上,我应该设计这个,这样我就可以用
$.getJSON(query, function(data) {
var columns = data.columns;
var results = data.results;
$.each(results, function(key, row) {
console.log(row[columns.indexOf('surname')]);
});
});
还是更漂亮
$.getJSON(query, function(data) {
var results = data.results;
$.each(results, function(key, row) {
console.log(row.surname);
});
});
?
从本质上说,我想知道对性能的潜在影响是否证明后一种选项的语法更加清晰.
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!.