为了账号安全,请及时绑定邮箱和手机立即绑定

如何组织相似的结构以避免重复而不牺牲内存

如何组织相似的结构以避免重复而不牺牲内存

Go
Smart猫小萌 2023-08-07 16:44:35
我必须重构代码,但我不知道如何最好地定义我的结构。我有一个米表[]Meter和Metertype Meter struct {    ID          string    `json:"meter_id"`    ConsoProd   string    `json:"conso_prod"`    OperationID string    `json:"op_id"`    Measures    []Measure `json :"measures"`}第 3 个字段将始终位于此处,但“测量”有多种变体,具体取决于过程中的步骤。这是一般Measure结构:// Measure is a measure from a Meter    type Measure struct {        IndexName     string    `json:"index_name"`        IndexValue    int       `json:"index_value"`        Timestamp     time.Time `json:"timestamp"`        Delta         float64   `json:"delta"`        Redistributed float64   `json:"redistributed,omitempty"` // We don t need the redistributed field in Raw Measure    }首先,我们得到“原始值”type RawMeasure struct {    IndexName     string    `json:"index_name"`    IndexValue    int       `json:"index_value"`    Timestamp     time.Time `json:"timestamp"`    Delta         float64   `json:"delta"`}然后我们将计算重新分配的值,并将其存储到字段redistributed中该措施永远不会重新分配。另外,我有2个数据源。如果数据来自source2,它永远不会有IndexName / IndexValuetype RawMeasureFromSource2 struct {    Timestamp     time.Time `json:"timestamp"`    Delta         float64   `json:"delta"`}在这里我们可以看到我可以创建几个结构:(RawMeasure、RawMeasureFromSource2、Measure),然后我应该创建其他 3 米变量。由于我将管理大量数据,因此我需要小心优化内存,但这似乎会使我的代码变得更加复杂。有没有办法既获得简单的代码又优化内存使用?
查看完整描述

1 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

根据评论,每 10 分钟 1 次测量绝对不是很多。我会为了简单起见:


type Measure struct {

    IndexName     *string    `json:"index_name,omitempty"`

    IndexValue    *int       `json:"index_value,omitempty"`

    Timestamp      time.Time `json:"timestamp"`

    Delta          float64   `json:"delta"`

    Redistributed *float64   `json:"redistributed,omitempty"`

}

优点:


结构相同,易于使用

缺点:


每个结构实例上丢失了几个字节


查看完整回答
反对 回复 2023-08-07
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信