As far as I know Nim in some cases can use smart Copy-on-Write, so you can 
write simple code without the references and it will be efficient.

I wrote a data processing example, with large chunks of immutable data (stock 
prices) passed around. The only non-immutable part is the cache for fast, lazy, 
on-demand loading. So, **ideally - there shouldn 't be much copying as the data 
is immutable**.

The code shouldn't be affected by the size of the data chunks, unless there are 
lots of copying. When the N increased - it becomes much slower. Why? Should the 
refs be used to make it faster?

[playground](https://play.nim-lang.org/#ix=2Lud)
    
    
    import tables, strformat, sequtils, sugar
    
    # The code would take much longer to run if N changed to 100_000, although
    # theoretically it shoulnd't affect the execution time (unless there are 
lots of copying).
    const N = 1000
    
    type
      Time = tuple[year: int, month: int, day: int, hour: int, minute: int, 
second: int]
      
      StockPrices* = object
        symbol*: string
        prices*: seq[(Time, float)]
    
    proc load_stock_prices_slow*(symbol: string): StockPrices =
      StockPrices(
        symbol: symbol,
        prices: (1..N).to_seq.map((i) => ((2000,1,1,1,1,i), 1.0))
      )
    
    # 1 should `ref` be used as table value?
    var prices_cache = init_table[string, StockPrices]()
    
    # 2 should `ref` be used for `proc` return type?
    proc get_prices*(symbol: string): StockPrices =
      if symbol notin prices_cache:
        prices_cache[symbol] = load_stock_prices_slow(symbol)
      prices_cache[symbol]
    
    # 3 should `ref` be used for `prices` argument?
    proc find_price_anomalies(prices: seq[(Time, float)]): bool = false
    
    # Usage - the `get_prices` functino called many times in different places.
    for _ in 1..1000:
      for i in 1..100:
        let symbol = fmt"S{i}"
        # 4 should `ref` be used here?
        let prices = get_prices(symbol)
        discard prices.prices[2]
        discard find_price_anomalies(prices.prices)
    
    echo "done"
    
    
    Run

Reply via email to