V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
iOS 开发实用技术导航
NSHipster 中文版
http://nshipster.cn/
cocos2d 开源 2D 游戏引擎
http://www.cocos2d-iphone.org/
CocoaPods
http://cocoapods.org/
Google Analytics for Mobile 统计解决方案
http://code.google.com/mobile/analytics/
WWDC
https://developer.apple.com/wwdc/
Design Guides and Resources
https://developer.apple.com/design/
Transcripts of WWDC sessions
http://asciiwwdc.com
Cocoa with Love
http://cocoawithlove.com/
Cocoa Dev Central
http://cocoadevcentral.com/
NSHipster
http://nshipster.com/
Style Guides
Google Objective-C Style Guide
NYTimes Objective-C Style Guide
Useful Tools and Services
Charles Web Debugging Proxy
Smore
jox
V2EX  ›  iDev

比 stringByReplacingPercentEscapesUsingEncoding: 更快的 url decoding 代码

  •  
  •   jox · 2014-12-24 20:36:04 +08:00 · 3876 次点击
    这是一个创建于 3625 天前的主题,其中的信息可能已经有所发展或是发生改变。
    之前一直这样进行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];
    }
    <<<<<<
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5486 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:01 · PVG 17:01 · LAX 01:01 · JFK 04:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.