如果我有一个不可变的字符串,那么每次调用hash时都会运行哈希算法,或者它是否记住了值(假设字符串不能更改)?
它被重新计算.
- [NSString hash]实际上是对[NSCFString hash]的调用(由于免费桥接).
如果您创建一个程序,在同一个字符串上调用 - [NSString hash],并且您在调用之间中断并更改备份字符串的内存,则会获得重新计算的哈希值.这告诉我没有涉及缓存.
(gdb) b -[NSCFString hash] Breakpoint 1 at 0x3b02fa3 (gdb) r Breakpoint 1, 0x93652fa3 in -[NSCFString hash] () (gdb) c Continuing. 2009-05-13 14:23:39.003 a.out[1754:813] Hash: -327163326
请注意哈希值.
Breakpoint 1, 0x93652fa3 in -[NSCFString hash] () (gdb) bt #0 0x93652fa3 in -[NSCFString hash] () #1 0x00001f73 in main () at test.m:10 (gdb) fra 1 #1 0x00001f73 in main () at test.m:10 10 NSLog(@"Hash: %d", [m hash]); (gdb) info locals pool = (NSAutoreleasePool *) 0x109760 m = (NSString *) 0x2030 (gdb) x/20x 0x2030 0x2030: 0xa06f54a0 0x000007c8 0x00001fa2 0x00000012
0xa06f54a0是"isa"指针,0x00001fa2是指向"XXXXXX"字符串的指针.
(gdb) set {int}0x1fa2 = 0x59595959
将"XXXXXX"字符串更改为"YYYYXXXX",然后继续第二次哈希调用
(gdb) c Continuing. 2009-05-13 14:24:35.884 a.out[1754:813] Hash: -246144954
注意,就ObjC而言,哈希值是不同的,知道不可变的字符串.
我(de)窃听的程序是:
#importint main() { NSAutoreleasePool * pool = [NSAutoreleasePool new]; NSString * m = [NSString stringWithString:@"XXXXXXXXXXXXXXXXXX"]; NSLog(@"Hash: %d", [m hash]); NSLog(@"Hash: %d", [m hash]); [pool release]; }