比 stringByReplacingPercentEscapesUsingEncoding: 更快的 url decoding 代码

2014-12-24 20:36:04 +08:00
 jox
之前一直这样进行url decoding:

>>>> return [[string stringByReplacingOccurrencesOfString:@"+" withString:@" "] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

今天在写一个简单的parser用来处理一段文本,顺手就写了段代码用来替代上面这段代码,上面这段代码 stringByReplacingPercent...这个方法问题不大,用来解码我用来测试的一大段文本需要8ms,但是将'+'替换成' '的效率奇差,拖慢了解码的速度,总共需要40ms才能完成解码,下面的这段代码解码同一段文本只需要12ms,其中百分号替换只需要6ms,比stringByReplacingPercent。。这个方法还快2ms。

这样子
>>>>>>
- (NSString *)urldecode:(NSString *)string {
if (!string || (id)string == [NSNull null] || string.length == 0) {
return nil;
}

static const unsigned char hexValue['f' - '0' + 1] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,0,0,0,0,0,0, 10, 11, 12, 13, 14, 15};
const unsigned char *source = (const unsigned char *)[string UTF8String];
NSUInteger length = [string maximumLengthOfBytesUsingEncoding: NSUTF8StringEncoding];
unsigned char output[length];
int indexOutput = 0;
int indexSource = 0;
unsigned char thisChar = source[indexSource];
while (thisChar != '\0') {
if (thisChar == '+') {
output[indexOutput] = ' ';
} else if (thisChar == '%') {
output[indexOutput] = (hexValue[source[indexSource + 1] - '0'] << 4) + hexValue[source[indexSource + 2] - '0'];
indexSource = indexSource + 2;
} else {
output[indexOutput] = thisChar;
}
indexOutput = indexOutput + 1;
indexSource = indexSource + 1;
thisChar = source[indexSource];
}
output[indexOutput] = '\0';

return [NSString stringWithUTF8String:(const char *)output];
}
<<<<<<
3738 次点击
所在节点    iDev
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/156421

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX