问题描述
我在记忆中保存着庞大的公司清单,并且需要做很多操作来获得单个公司。
就像用符号“ MSFT”获得单个公司“ Microsoft”一样。
下面的数据结构是建模的合适方法吗?整个list
或map
的按值复制。
可以通过价值复制单个公司。
import tables
type
Company = object
name: string
symbol: string
description: string
CompaniesRef = ref object
list: seq[Company]
map: Table[string,Company]
# Cached data structure to keep thousands of different companies
var cached_companies: CompaniesRef
proc companies(): CompaniesRef =
if cached_companies == nil:
# Here will be a proper code of loading companies into the
# CompaniesRef data structure
cached_companies = CompaniesRef()
cached_companies
# Lots of operations of getting a specific company from the list
# or from the map by its symbol
for i in 1..1000:
# it's ok if individual company will be copied by value,# but the whole list should be passed by reference
let company1 = companies().list[0].name
# it's ok if individual company will be copied by value
# but the whole map should be passed by reference
let company2 = companies().map["MSFT"]
解决方法
该全局结构应该是正确的,对象引用只是一个内存管理的指针,因此传递其引用仅会复制内存地址。除非您打算使用该指针做某事,否则为什么不将其创建为全局指针呢?将其隐藏在我很怕全局但无法在没有它们的情况下生存模式的proc调用后。
let companies = CompaniesRef()
关于结构的内容,您要为每个Company
对象存储两次,您可能希望将对Company
的引用存储在Table
中,或仅使用{ {3}},如果您需要保持插入键的顺序。