It seems like JSON in Nim is really slow.

It's a bit unfair to compare with Node.JS, as in Node JSON parsed by heavily 
optimised C code. Yet, I think the numbers should be more or less comparable, 
not orders of magnitude slower. The scripts below are 30 times slower with 
`-d:release` and 160 times slower without it.

Nim timing
    
    
    > nim r play.nim
    Time taken: 5.182976999999999 sec
    
    > nim -d:release r play.nim
    Time taken: 0.845689 sec
    
    
    Run

Node.JS timing
    
    
    deno run tmp/play.ts
    Time taken: 0.032 sec
    
    
    Run

Nim code
    
    
    import times, os, std/json, std/jsonutils
    
    type OptionContract* = ref object
      id*:               string
      right*:            string
      expiration*:       string
      strike_raw*:       float
      premium_raw*:      float
      data_type*:        string
    
    type OptionChain* = object
      contracts*: seq[OptionContract]
    
    proc stub_data(): OptionChain =
      result = OptionChain()
      for _ in 1..6000:
        result.contracts.add OptionContract(
          id: "AMZN CALL 2021-03-19 1460.0 USD",
          right: "call",
          expiration: "2021-03-19",
          strike_raw: 1460.0,
          premium_raw: 1676.03,
          data_type: "some type"
        )
    let json_str = stub_data().to_json.pretty
    
    let time = cpuTime()
    for i in 1..5:
      discard json_str.parse_json.json_to(OptionChain)
    echo "Time taken: ", cpuTime() - time, " sec"
    
    
    Run

Node.JS code
    
    
    interface OptionContract {
      id:               string
      right:            string
      expiration:       string
      strike_raw:       number
      premium_raw:      number
      data_type:        string
    }
    
    interface OptionChain {
      contracts: OptionContract[]
    }
    
    function stub_data(): OptionChain {
      let contracts: OptionContract[] = []
      for (let i = 0; i < 6000; i++) contracts.push({
        id: "AMZN CALL 2021-03-19 1460.0 USD",
        right: "call",
        expiration: "2021-03-19",
        strike_raw: 1460.0,
        premium_raw: 1676.03,
        data_type: "some type"
      })
      return { contracts }
    }
    let json_str = JSON.stringify(stub_data(), null, 2)
    
    let time = Date.now()
    for (let i = 0; i < 5; i++) {
      JSON.parse(json_str)
        // In JS the JSON parsed by native C-code, so let's
        // do some work in JS-land
        .contracts.map((c: any) => ({...c, id: "abc " + c.id }))
    }
    console.log(`Time taken: ${(Date.now() - time) / 1000} sec`)
    
    
    Run

Reply via email to