alphadose / haxmap

Fastest and most memory efficient golang concurrent hashmap
MIT License
892 stars 45 forks source link

Add clear all method #43

Closed fxfactorial closed 1 month ago

fxfactorial commented 6 months ago

fantastic library , can you add a drop all/clear method.

Say after n period of time, I want to clear out everything but not resize down .

Demy076 commented 6 months ago
func (m Map[K, V]) Keys() (keys []K, length uintptr) {
    length = m.Len()
    keys = make([]K, length)
    var (
        idx  = 0
        item = m.listHead.next()
    )
    for item != nil {
        keys[idx] = item.key
        idx++
        item = item.next()
    }
    return
}

func (m *Map[K, V]) Clear() {
    keys, _ := m.Keys()
    m.Del(keys...)
}

I added them to fit my needs but afaik they work for me

semihbkgr commented 6 months ago

Hi @Demy076

I don't think that it is an efficient way to clear the map. It would be better to create new empty indexes and load into the map.

func (m *Map[K, V]) Clear() {
    index := make([]*element[K, V], defaultSize)
    header := (*reflect.SliceHeader)(unsafe.Pointer(&index))

    newdata := &metadata[K, V]{
        keyshifts: strconv.IntSize - log2(defaultSize),
        data:      unsafe.Pointer(header.Data),
        index:     index,
    }

    m.listHead.nextPtr.Store(nil)
    m.metadata.Store(newdata)
    m.numItems.Store(0)
}