这是使用 Nim ref 数据结构的有效方法吗?
Is this efficient way to use Nim ref data structure?
我在内存中保存了大量的公司列表,需要做很多获取单个公司的操作。
比如通过其符号“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"]
那个全局结构应该没问题,一个对象引用只是一个内存管理指针,所以传递它的引用只会复制内存地址。除非你打算用那个指针做点什么,为什么不把它创建为一个全局指针呢?将它隐藏在 I'm-afraid-of-globals-but-can't-live-without-them-singleton 模式的 proc 调用后面。
let companies = CompaniesRef()
关于结构的内容,每个 Company
对象存储两次,您可能希望在 Table
中存储对 Company
的引用或简单地使用OrderedTable 如果您需要保持插入键的顺序。
我在内存中保存了大量的公司列表,需要做很多获取单个公司的操作。
比如通过其符号“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"]
那个全局结构应该没问题,一个对象引用只是一个内存管理指针,所以传递它的引用只会复制内存地址。除非你打算用那个指针做点什么,为什么不把它创建为一个全局指针呢?将它隐藏在 I'm-afraid-of-globals-but-can't-live-without-them-singleton 模式的 proc 调用后面。
let companies = CompaniesRef()
关于结构的内容,每个 Company
对象存储两次,您可能希望在 Table
中存储对 Company
的引用或简单地使用OrderedTable 如果您需要保持插入键的顺序。