nim-lang - 这是使用 Nim ref 数据结构的有效方法吗?
问题描述
我在记忆中保留了大量公司,并且需要做大量的操作来获得单个公司。
就像通过其符号“MSFT”获得个别公司“Microsoft”。
下面的数据结构是否是对其建模的正确方法?list
整个or不应该有按值复制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 调用后面会散发出I'm-afraid-of-globals-but-can't-live-without-them-singleton模式的味道。
let companies = CompaniesRef()
关于结构的内容,您要存储每个对象两次,如果您需要保持插入键的顺序Company
,您可能希望存储对Company
in 的引用Table
或简单地使用OrderedTable 。