是[NSString hash]计算每次? [英] Is [NSString hash] computed every time?
问题描述
如果我有一个不可变的字符串是哈希算法运行每次我调用哈希,或者记住该值(假定字符串不能更改)?
- [NSString hash]实际上是一个调用 - [NSCFString hash](由于自由桥接)。
如果你创建一个程序在同一个字符串上调用 - [NSString hash],并且打断了调用和更改内存备份字符串,你得到一个重新计算的哈希值。
(gdb)b - [NSCFString hash]
Breakpoint 1 at 0x3b02fa3
(gdb)r
断点1,0x93652fa3 - [NSCFString hash]()
(gdb)c
继续。
2009-05-13 14:23:39.003 a.out [1754:813]散列:-327163326
注意哈希值。
断点1,0x93652fa3 - [NSCFString hash]()
(gdb)bt
#0 0x93652fa3 in - [NSCFString hash]()
#1 0x00001f73在main.m()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是isa指针,0x00001fa2是指向XXXXXX字符串。
(gdb)set {int} 0x1fa2 = 0x59595959
将XXXXXX字符串更改为YYYYXXXX,然后继续第二个哈希调用
(gdb)c
续。
2009-05-13 14:24:35.884 a.out [1754:813]哈希:-246144954
请注意,在ObjC中知道不可变字符串的哈希值是不同的。
我已经编写的程序是: p>
#import< Cocoa / Cocoa.h>
int main()
{
NSAutoreleasePool * pool = [NSAutoreleasePool new];
NSString * m = [NSString stringWithString:@XXXXXXXXXXXXXXXXXX];
NSLog(@Hash:%d,[m hash]);
NSLog(@Hash:%d,[m hash]);
[pool release];
}
If I have an immutable string is the hashing algorithm run every time I call hash, or does it remember the value (given that the string can't change)?
It is recomputed.
-[NSString hash] is in fact a call to -[NSCFString hash] (due to toll free bridging).
If you create a program that calls -[NSString hash] on the same string and you break in between the calls and alter the memory backing up the string, you get a re-computed hash value. This tells me there's no caching involved.
(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
Note the hash value.
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 <dyld__mach_header+32>: 0xa06f54a0 0x000007c8 0x00001fa2 0x00000012
0xa06f54a0 is the "isa" pointer, 0x00001fa2 is a pointer to the "XXXXXX" string.
(gdb) set {int}0x1fa2 = 0x59595959
alter the "XXXXXX" string to "YYYYXXXX", then continue to the second hash call
(gdb) c
Continuing.
2009-05-13 14:24:35.884 a.out[1754:813] Hash: -246144954
Note the hash value that is different on the as far as ObjC knows immutable string.
The program I've (de)bugged is:
#import <Cocoa/Cocoa.h>
int main()
{
NSAutoreleasePool * pool = [NSAutoreleasePool new];
NSString * m = [NSString stringWithString:@"XXXXXXXXXXXXXXXXXX"];
NSLog(@"Hash: %d", [m hash]);
NSLog(@"Hash: %d", [m hash]);
[pool release];
}
这篇关于是[NSString hash]计算每次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!