如何使这段代码更高效?

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

How to make this code more performant?

问题

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

  1. func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
  2. for k, _ := range filter {
  3. if relationString(msg) == k {
  4. if fieldFilter, ok := filter[k]; ok {
  5. for _, f := range msg.Fields {
  6. if _, ok := fieldFilter[f.Name]; ok {
  7. fs = append(fs, f)
  8. }
  9. }
  10. }
  11. }
  12. }
  13. return
  14. }
英文:

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.

  1. func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
  2. for k, _ := range filter {
  3. if relationString(msg) == k {
  4. if fieldFilter, ok := filter[k]; ok {
  5. for _, f := range msg.Fields {
  6. if _, ok := fieldFilter[f.Name]; ok {
  7. fs = append(fs, f)
  8. }
  9. }
  10. }
  11. }
  12. }
  13. return
  14. }

答案1

得分: 1

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

  1. func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
  2. if fieldFilter, ok := filter[relationString(msg)]; ok {
  3. for _, f := range msg.Fields {
  4. if _, ok := fieldFilter[f.Name]; ok {
  5. fs = append(fs, f)
  6. }
  7. }
  8. }
  9. return
  10. }
英文:

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

  1. func getFields(filter map[string]map[string]bool, msg *Message) (fs []Field) {
  2. if fieldFilter, ok := filter[relationString(msg)]; ok {
  3. for _, f := range msg.Fields {
  4. if _, ok := fieldFilter[f.Name]; ok {
  5. fs = append(fs, f)
  6. }
  7. }
  8. }
  9. }
  10. return
  11. }

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:

确定