What is the fastest way to convert a long long to NSString

[亡魂溺海] 提交于 2019-12-13 08:17:35

问题


I need to convert a lot of long long's to NSString. What is the fastest way to do this? I am aware of two ways to do this and I am wondering if there is anything else that would be faster.

NSString* str = [NSString stringWithFormat:@"%lld", val];

And

NSString* str = [[NSNumber numberWithLongLong:val] stringValue];

where val is a long long (64 bit int). The first method has the small overhead of parsing the string and the second has the overhead of allocating an additional object. Most likely NSNumber uses NSString's stringWithFormat, but I am not sure.

Does anyone know of a faster method for this?


回答1:


I put together a basic profiling app. I tried your two approaches, and Rob Mayoff's two approaches.

stringWithFormat: took an average of 0.000008 seconds. The other three approaches (calling stringValue on numberWithLongLong:), and Rob's two, all took an average of 0.000011 seconds.

Here's my code. It's obviously not 100% accurate since there are a few other operations included in the profile, but the discrepancies will be the same in all of the tests:

- (void) startProfiling {
    self.startDate = [NSDate date];
}

- (NSTimeInterval) endProfiling {
    NSDate *endDate = [NSDate date];
    NSTimeInterval time = [endDate timeIntervalSinceDate:self.startDate];
    self.startDate = nil;
    NSLog(@"seconds: %f", time);
    return time;
}

- (void)doTest:(id)sender {
    long long val = 1234567890987654321;

    NSTimeInterval totalTime = 0;

    for (int i = 0; i < 1000; i++) {
        [self startProfiling];

        // change this line for each test
        NSString* str = [NSString stringWithFormat:@"%lld", val];

        totalTime += [self endProfiling];
    }

    NSLog(@"average time: %f", totalTime / 1000);
}



回答2:


This is the fastest to type:

NSString *string = @(val).description;

This requires one additional keystroke:

NSString *string = @(val).stringValue;

If you mean the fastest at run time, the only way to be sure is to try it both ways and see. Profile. Don't speculate.



来源:https://stackoverflow.com/questions/20550617/what-is-the-fastest-way-to-convert-a-long-long-to-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!