Friday, April 19, 2024
HomeGolangEnhancing efficiency of a operate - Getting Assist

Enhancing efficiency of a operate – Getting Assist


Hello,

I’ve a operate and want to enhance its efficiency and reminiscence allocation if potential. It was allocating 23 earlier than and I did my greatest to carry it down to eight now however I nonetheless assume the operate nonetheless may be improved. I’d respect if I can get assist with that please.

Thanks

bundle logger

import (
	"type"
	"strconv"
)

kind Area map[string]interface{}

func log(line string, fields Area) string {
	keys := make([]string, 0, len(fields))
	for ok := vary fields {
		keys = append(keys, ok)
	}
	type.Strings(keys)

	for _, ok := vary keys {
		if val, okay := fields[k].(string); okay {
			line += `,"` + ok + `":"` + val + `"`
			proceed
		}
		if val, okay := fields[k].(int); okay {
			line += `,"` + ok + `":` + strconv.Itoa(val)
			proceed
		}
		if val, okay := fields[k].(float64); okay {
			line += `,"` + ok + `":` + string(strconv.AppendFloat([]byte(``), val, 'f', -1, 64))
			proceed
		}
		if val, okay := fields[k].(bool); okay {
			line += `,"` + ok + `":` + strconv.FormatBool(val)
			proceed
		}
	}

	return line
}

bundle logger

import "testing"

func Benchmark_log(b *testing.B) {
	for i := 0; i < b.N; i++ {
		log("hi there", Area{"str": "val" , "int": 1, "flo": 1234567890.01234567,"bol": true})
	}
}
$ go check -v -bench=. -benchmem ./logger/
goos: darwin
goarch: amd64
pkg: loog/logger
cpu: Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
Benchmark_log
Benchmark_log-4   	  924964	      1246 ns/op	     328 B/op	       8 allocs/op
PASS
okay  	loog/logger	2.420s

They already use a preallocated slice (third argument to make)

Will most likely make issues even worse, because it grows by the common guidelines of slices and can’t be correctly made with a much bigger capability estimate.

Although certainly impleminting one thing comparable that really had a approach to create an “empty” builder with a preguesses capability may assist with getting allocations down.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments