如何使这段代码更高效?

huangapple go评论82阅读模式
英文:

How to make this code more performant?

问题

我有这样一段代码,它遍历一个映射并根据关系类型过滤一些字段,我必须运行两个循环,并且对于大型映射来说,我觉得速度会很慢。有没有什么方法/重构可以使这段代码更高效。

func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {

    for k, _ := range filter {
        if relationString(msg) == k {
            if fieldFilter, ok := filter[k]; ok {
                for _, f := range msg.Fields {
                    if _, ok := fieldFilter[f.Name]; ok {
                        fs = append(fs, f)
                    }
                }
            }
        }
    }
    return
}
英文:

I have this snippet of code that iterate over a map and filter some fields based on relation type, I have to run two loops and have a feeling that it is going to be slow for big maps. Is there any way I can technique/refactoring to make this code more performant.

func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {

	for k, _ := range filter {
		if relationString(msg) == k {
			if fieldFilter, ok := filter[k]; ok {
				for _, f := range msg.Fields {
					if _, ok := fieldFilter[f.Name]; ok {
						fs = append(fs, f)
					}
				}
			}
		}
	}
	return
}

答案1

得分: 1

你不需要外部循环作为一种改进:

func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
  if fieldFilter, ok := filter[relationString(msg)]; ok {
    for _, f := range msg.Fields {
      if _, ok := fieldFilter[f.Name]; ok {
        fs = append(fs, f)
      }
    }
  }
  
  return
}
英文:

You don't need the outer loop as one improvement:

func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
  if fieldFilter, ok := filter[relationString(msg)]; ok {
    for _, f := range msg.Fields {
        if _, ok := fieldFilter[f.Name]; ok {
            fs = append(fs, f)
        }
      }
    }
  }
  
  return
}

huangapple
  • 本文由 发表于 2015年6月15日 23:30:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/30849122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定