之前一直这样进行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];
}
<<<<<<