I have a function returning table of companies that's **called many times** to 
get information about different companies:
    
    
    echo companies()["MSFT"].name
    echo companies()["INTC"].name
    ...
    
    
    Run

How the result of `companies` function should be defined, as Value or Reference?
    
    
    proc companies(): Table[string, Company] = ...
    
    
    Run

or as
    
    
    proc companies(): ref Table[string, Company] = ...
    
    
    Run

I guess it should be defined as `ref Table[string, Company]` because 
**otherwise the whole huge table containing all the companies will be copied** 
every time when the function is called, right?

Full code
    
    
    import tables
    
    proc to_ref*[T](o: T): ref T =
      result.new
      result[] = o
    
    type
      Company* = object
        symbol*:      string # MSFT
        name*:        string # Microsoft
        # ... many more fields
    
    var cached_companies: ref Table[string, Company]
    
    proc companies*(): Table[string, Company] =
      if cached_companies == nil:
        cached_companies = {
          "MSFT": Company(name: "Microsoft", symbol: "MSFT")
          # Couple hundreds more companies ....
        }.to_table.to_ref
      cached_companies[]
    
    # Many thousands calls to get details about
    # different companies
    for i in 1..3:
      echo companies()["MSFT"]
    
    
    Run

Reply via email to