尝试实现一个应用程序,该应用程序在连接到Internet时将存储在本地数据库中的脱机数据发送到Web服务器我使用下面显示的代码.到目前为止,我测试它工作正常,不确定它将适用于大量的记录.我想知道是否对此代码进行任何调整可能会提高性能???
注意
>我知道这将是用于离线同步目的的最差代码,所以尝试
更好地调整它.
>从应用程序到服务器的单向同步.
-(void)FormatAnswersInJSON { DMInternetReachability *checkInternet = [[DMInternetReachability alloc] init]; if ([checkInternet isInternetReachable]) { if ([checkInternet isHostReachable:@"www.apple.com"]) {//Change to domain responseArray = [[NSMutableArray alloc] init]; dispatch_async(backgroundQueue,^(void) { NSArray *auditIDArray = [[NSArray alloc] initWithArray: [self getUnuploadedIDs]]; for (int temp = 0; temp < [auditIDArray count]; temp ++) { // Code to post JSON to server NSURLResponse *response; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (!error) { NSString *responseID = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; if ([responseID isEqualToString:@"ERROR"]) { //Error uploading records } else { [responseArray addObject:responseID]; } } else { //Error return; } } dispatch_async( backgroundQueue,^{ /* Based on return code update local DB */ for (int temp = 0; temp < [responseArray count]; temp ++) { [self updateRecordsForID:[auditIDArray objectAtIndex:temp] withID:[responseArray objectAtIndex:temp]]; } }); }); } } } - (void)upload { //Called when internet connection available if(backgroundQueue){ dispatch_suspend(backgroundQueue); dispatch_release(backgroundQueue); backgroundQueue = nil; } backgroundQueue = dispatch_queue_create("com.XXXX.TestApp.bgqueue",NULL); dispatch_async(backgroundQueue,^(void) { [self FormatAnswersInJSON]; }); }
解决方法
如果这个代码放在我面前,我的方法是:
>查看用例并定义“大量记录”:是否会定期更新50条记录?或者是1s和2s?我的用户是否有wifi连接或是通过付费网络?等
>如果可能的话,在野外进行测试.如果我的用户群足够小,请收集实际数据并指导我的决策,或者仅将功能发布到用户/ beta测试和测量的子集.
>如果数据告诉您,则优化此代码以提高效率.
我的优化途径是进行组处理.粗略的算法将是这样的:
for records in groups of X collect post to server { on return: gather records that updated successfully update locally }
这假设您可以修改服务器代码.你可以做10,20,50等组,所有这些都取决于发送的数据类型和大小.
组算法意味着更多的预处理客户端,但具有减少HTTP请求的优点.如果您只是获得少量更新,那么这是YAGNI和预成熟优化.
不要让这个决定阻止你运输!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。