Swift 是否有办法避免快速保留/发布高性能代码?
我想写一个经典缓存数据结构的Swift版本,它使用一个数组直到某个可配置的限制,然后切换到一个映射[2]。 不幸的是,我在编写更简单的数据结构时得到的性能特征使我认为这在swift中目前是不可行的 考虑这段代码:Swift 是否有办法避免快速保留/发布高性能代码?,swift,performance,caching,Swift,Performance,Caching,我想写一个经典缓存数据结构的Swift版本,它使用一个数组直到某个可配置的限制,然后切换到一个映射[2]。 不幸的是,我在编写更简单的数据结构时得到的性能特征使我认为这在swift中目前是不可行的 考虑这段代码: import Foundation let aKey = 196 var cache: [(Int, String)] = [] for _ in 0..<1_000_000_000 { var t: String? for (k, v) in cache
import Foundation
let aKey = 196
var cache: [(Int, String)] = []
for _ in 0..<1_000_000_000
{
var t: String?
for (k, v) in cache
{
if k == aKey
{
t = v
break
}
}
if t == nil
{
let str = "some cache value with key=\(aKey)"
cache.append((aKey, str))
t = str
}
}
<代码>导入基础
让aKey=196
变量缓存:[(Int,String)]=[]
对于0中的uu。。v
{
得到
{
对于数组中的(k,v)
{
如果k==索引
{
返回v
}
}
归零
}
设置(新值)
{
array.append((索引,newValue))
}
}
}
让aKey=196
变量缓存:DummyCache=DummyCache()
cache[aKey]=“一些键为\(aKey)的缓存值”
对于0中的uu。。v
init(limit:Int=20,buildValueFromKey:@escaping(K)->V)//最佳限制取决于,必须进行测试以找到最佳值
{
self.limit=限制
self.buildValueFromKey=buildValueFromKey
}
下标(索引:K)->V
{
突变基因
{
如果var map=map
{
如果let res=map[index]
{
返回res
}
其他的
{
设res=buildValueFromKey(索引)
映射[索引]=res
返回res
}
}
else//数组模式
{
如果数组==nil
{
设res=buildValueFromKey(索引)
数组=[(索引,res)]
返回res
}
//否则
对于数组中的(k,v)//此时不能为null
{
如果k==索引
{
返回v
}
}
//数组此时不包含索引,请创建并追加它
设res=buildValueFromKey(索引)
数组!.append((索引,res))
返回res
}
}
}
}
让aKey=196
var cache:cache=cache{“某个键为\($0)”的缓存值]
对于0中的uu。。
import Foundation
struct DummyCache<K:Hashable, V>
{
var array:[(K, V?)] = []
subscript(index: K) -> V?
{
get
{
for (k, v) in array
{
if k == index
{
return v
}
}
return nil
}
set(newValue)
{
array.append((index, newValue))
}
}
}
let aKey = 196
var cache: DummyCache<Int, String> = DummyCache()
cache[aKey] = "some cache value with key=\(aKey)"
for _ in 0..<1_000_000_000
{
var t: String? = cache[aKey]
}
import Foundation
struct Cache<K:Hashable, V>
{
let limit: Int
var array:[(K, V)]? = nil
var map: [K:V]? = nil
let buildValueFromKey: (K) -> V
init(limit: Int = 20, buildValueFromKey:@escaping (K) -> V) //optimal limit depends, must conduct tests to find optimal value
{
self.limit = limit
self.buildValueFromKey = buildValueFromKey
}
subscript(index: K) -> V
{
mutating get
{
if var map = map
{
if let res = map[index]
{
return res
}
else
{
let res = buildValueFromKey(index)
map[index] = res
return res
}
}
else //array mode
{
if array == nil
{
let res = buildValueFromKey(index)
array = [(index, res)]
return res
}
//else
for (k, v) in array! //can't be null at that point
{
if k == index
{
return v
}
}
// array does not contain index at this point, create & append it
let res = buildValueFromKey(index)
array!.append((index, res))
return res
}
}
}
}
let aKey = 196
var cache: Cache<Int, String> = Cache{ "some cache value with key=\($0)" }
for _ in 0..<1_000_000_000
{
var t: String? = cache[aKey]
}