在iOS发行版中稳定的String的哈希值? [英] Hash value of String that would be stable across iOS releases?

查看:146
本文介绍了在iOS发行版中稳定的String的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS的文档String.hash中说:

您不应该依赖此属性在所有属性上具有相同的哈希值 OS X版本.

You should not rely on this property having the same hash value across releases of OS X.

(奇怪的是为什么他们在iOS文档中提到OS X)

(strange why they speak of OS X in iOS documentation)

嗯,我需要一个哈希功能,该功能在iOS版本中不会更改.可以很简单,我不需要任何类似SHA的东西.有图书馆吗?

Well, I need a hasshing function that will not change with iOS releases. It can be simple I do not need anything like SHA. Is there some library for that?

此处还有另一个问题,但是那里被接受的(唯一的)回答只是表明我们应该尊重文档中的注释.

There is another question about this here but the accepted (and only) answer there simply states that we should respect the note in documentation.

推荐答案

这是Swift 3的非加密哈希值:

Here is a non-crypto hash, for Swift 3:

 func strHash(_ str: String) -> UInt64 {
    var result = UInt64 (5381)
    let buf = [UInt8](str.utf8)
    for b in buf {
        result = 127 * (result & 0x00ffffffffffffff) + UInt64(b)
    }
    return result
 }

它有点源自C ++ 11 constexpr

It was derived somewhat from a C++11 constexpr

    constexpr uint64_t str2int(char const *input) {
    return *input                      // test for null terminator
    ? (static_cast<uint64_t>(*input) + // add char to end
       127 * ((str2int(input + 1)      // prime 127 shifts left almost 7 bits
               & 0x00ffffffffffffff))) // mask right 56 bits
    : 5381;                            // start with prime number 5381
}

不幸的是,两者并没有产生相同的哈希值.为此,您需要反转strHash中的迭代器顺序:

Unfortunately, the two don't yield the same hash. To do that you'd need to reverse the iterator order in strHash:

for b in buf.reversed() {...}

但是运行速度会慢13倍,与我从 https://useyourloaf.com/blog/swift-hashable/

But that will run 13x slower, somewhat comparable to the djb2hash String extension that I got from https://useyourloaf.com/blog/swift-hashable/

这里有一些基准,可以进行一百万次迭代:

Here are some benchmarks, for a million iterations:

hashValue execution time: 0.147760987281799
strHash execution time:   1.45974600315094
strHashReversed time:    18.7755110263824
djb2hash execution time: 16.0091370344162
sdbmhash crashed

对于C ++,str2Int大约与Swift 3的hashValue一样快:

For C++, the str2Int is roughly as fast as Swift 3's hashValue:

str2int execution time: 0.136421

这篇关于在iOS发行版中稳定的String的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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