NSString内部-长度如何工作? [英] NSString internals - how does length works?

查看:50
本文介绍了NSString内部-长度如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对NSString内部有疑问。
我想检查一个字符串的长度,基本上我想知道NSString是否每次都知道其长度/计数/计数&

I've a question about NSString internals. I want to check a string length and basically I wanted to know if a NSString knows its length / count each time / count & cache the result.

我应该存储它的长度并每次计算或调用length方法吗?

Should I store it's length and compute or call the length method each time ?

To测试一个字符串,我可以针对nil进行测试,也可以要求它的长度。

To test a string I can test against nil OR ask for it's length.

if (str != nil) {
  // compute
}

if ([str length]) {
  // compute
}

哪个是最快的?
哪个是内存效率更高的?

Which one is the fastest ? Which one is the more memory efficient ?

谢谢

推荐答案

检查 nil (无对象)绝对与发送长度相同 code>消息发送到(NSString)对象。条件检查中只有一项有效,可以测试空字符串。 (空字符串是一个对象,因此不是 nil 。)

Checking for nil ("no object") is most definitely not the same as sending the length message to the (NSString) object. Only one of the conditional checks is valid to test for an "empty" string. (An "empty" string is an object and, therefore, not nil.)

更大的问题是: NSString会存储长度吗?或者它是定点结尾的(例如普通c字符串)? NSString将长度存储为内部属性,因此它的长度 length 是O(1)操作。

The bigger question is: does NSString store a length or is it sentinel-terminated (like a "normal c string")? NSString stores the length as an internal property so it, length, is as O(1) operation.

Happy编码。

这篇关于NSString内部-长度如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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