我有以下代码从本地文件夹加载带有JSON的文件然后解析它:
async public static void TryLoad(Callback Ok, Action Fail, string key, int offset)
{
try
{
var now = DateTime.Now;
ItemsCache cacheItem;
var folder = ApplicationData.Current.LocalFolder;
var stream = await folder.OpenStreamForReadAsync(key);
using (stream)
{
var result = await new StreamReader(stream).ReadToEndAsync();
Debug.WriteLine("Raw data loaded: " + (DateTime.Now - now).TotalMilliseconds);
cacheItem = JsonConvert.DeserializeObject<ItemsCache>(result);
Debug.WriteLine("Json has been parsed: " + (DateTime.Now - now).TotalMilliseconds);
stream.Close();
}
bool isOK = cacheItem.IsValid(offset);
if (isOK) Ok(cacheItem.Data); else Fail();
}
catch (Exception)
{
Fail();
}
}
ItemsCache
本身:
public class ItemsCache
{
public string Stamp { get; set; }
public JToken Data { get; set; }
public bool IsValid(int ofs)
{
DateTime moment = DateTime.Parse(Stamp);
return (DateTime.Now - moment).TotalSeconds < ofs;
}
}
连续两次加载数据后的输出:
Raw data loaded: 356,7372
Json has been parsed: 855,588
Raw data loaded: 1269,6079
Json has been parsed: 1300,8621
JSON:
{"Stamp":"26.01.2013 20:49:26","Data":[{"id":188357911,"user":123145, ... a few more more key-value pairs}, ... the rest of the objects]}
事情是,整个过程大约需要750毫秒,其中150个用于加载原始数据,600个用于使用Newtonsoft JSON库解析它。数据量本身很小,包含大约20个序列化对象,这些对象本质上是一个小的键值对(虽然我发现我可以添加更多的数据,但它不会影响解析时间)。
问题是,如果花费那么多时间来加载数据并且需要更多时间来解析数据是否正常?如果这不正常我该怎么办?