I have this piece of code
    
    
    import std/monotimes
    import tables
    import random
    var myTable = initTable[int, int]()
    var myList: seq[int]
    
    for i in 0 .. 1_000_000:
        myTable[i] = i
        myList.add(i)
    
    myList.shuffle()
    
    var start = getMonoTime()
    for i in 0 ..< 1_000_000:
        discard myList.contains(i)
    echo("List: ", getMonoTime() - start)
    
    start = getMonoTime()
    for i in 0 ..< 1_000_000:
        discard myTable.hasKey(i)
    echo("Table: ", getMonoTime() - start)
    
    
    Run

Compile with this command nim c -d:release -r speed_test.nim

And here is my results 
    
    
    List: (seconds: 0, nanosecond: 9384)
    Table: (seconds: 0, nanosecond: 6553878)
    
    
    Run

My question is why linear search of seq is faster than constant search of 
tables?

I know how tables work and I understand that Tables has to calculate hash for 
each key But it is main feature of hash maps to give constant search. I 
shuffled list before search

P.S. When I asked this question on Gitter I faced aggression and sarcasm 
    
    
    <narimiran> shit, we have tables for no reason
    <disruptek> it's not that tables are expensive, it's that finding the first 
element in a seq is fast.
    
    
    Run

I sent this link 
[https://play.nim-lang.org/#ix=2r1w](https://play.nim-lang.org/#ix=2r1w) and if 
you look carefully my list has reverse order 
    
    
    for i in countdown(1_000_000, 0):
        myList.add(i)
    
    
    Run

It was rude and not very welcoming

Reply via email to