What is the fastest way to convert a long long to

2019-09-20 00:33发布

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?

2条回答
欢心
2楼-- · 2019-09-20 01:01

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);
}
查看更多
看我几分像从前
3楼-- · 2019-09-20 01:01

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.

查看更多
登录 后发表回答