如何避免我的数据结构中的嵌套映射分配?

我有一个下面的结构,其中有一个嵌套映射,CustomersIndex它分配了一堆内部映射,导致内存增加。我对它进行了分析,所以我注意到了这一点。我想看看是否有任何方法可以重新设计CustomersIndex不使用嵌套映射的数据结构?


const (

    departmentsKey = "departments"

)


type CustomerManifest struct {

    Customers      []definitions.Customer

    CustomersIndex map[int]map[int]definitions.Customer

}

这是我在下面的代码中填充它的方式:


func updateData(mdmCache *mdm.Cache) map[string]interface{} {

    memCache := mdmCache.MemCache()


    var customers []definitions.Customer

    var customersIndex = map[int]map[int]definitions.Customer{}


    for _, r := range memCache.Customer {

        customer := definitions.Customer{

            Id:           int(r.Id),

            SetId:        int(r.DepartmentSetId),

        }


        customers = append(customers, customer)

        _, yes := customersIndex[customer.SetId]

        if !yes {

            customersIndex[customer.SetId] = make(map[int]definitions.Customer)

        }

        customersIndex[customer.SetId][customer.Id] = customer

    }


    return map[string]interface{}{

        departmentsKey: &CustomerManifest{Customers: customers, CustomersIndex: customersIndex},

    }

}

这就是我获取CustomersIndex嵌套地图的方式。


func (c *Client) GetCustomerIndex() map[int]map[int]definitions.Customer {

    c.mutex.RLock()

    defer c.mutex.RUnlock()

    customersIndex := c.data[departmentsKey].(*CustomerManifest).CustomersIndex

    return customersIndex

}

有什么方法可以CustomersIndex让我不必使用嵌套地图来设计我的地图吗?


慕尼黑5688855
浏览 103回答 1
1回答

慕哥6287543

在将值放入其中之前,您不需要分配地图。type CustomerManifest struct {    Customers      []definitions.Customer    CustomersIndex map[int]map[int]definitions.Customer}func (m *CustomerManifest) AddCustomerDefinition(x, y int, customer definitions.Customer) {    // Get the existing map, if exists.    innerMap := m.CustomersIndex[x]    // If it doesn't exist, allocate it.    if innerMap == nil {        innerMap = make(map[int]definitions.Customer)        m.CustomersIndex[x] = innerMap    }    // Add the value to the inner map, which now exists.    innerMap[y] = customer}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go