将 long long 转换为 NSString 的最快方法是什么 [英] What is the fastest way to convert a long long to NSString

查看:110
本文介绍了将 long long 转换为 NSString 的最快方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将很多 long long 转换为 NSString.执行此操作的最快方法是什么?我知道有两种方法可以做到这一点,我想知道是否还有其他更快的方法.

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];

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

其中 val 是 long long(64 位 int).第一种方法解析字符串的开销很小,第二种方法分配额外对象的开销很小.很可能 NSNumber 使用 NSString 的 stringWithFormat,但我不确定.

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?

推荐答案

我组装了一个基本的分析应用程序.我尝试了你的两种方法,以及 Rob Mayoff 的两种方法.

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

stringWithFormat: 平均花费 0.000008 秒.其他三种方法(在 numberWithLongLong: 上调用 stringValue)和 Rob 的两种方法,平均花费了 0.000011 秒.

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.

这是我的代码.这显然不是 100% 准确,因为配置文件中还包含一些其他操作,但所有测试中的差异都相同:

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);
}

这篇关于将 long long 转换为 NSString 的最快方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆