I have a lot of datetime values incoming as string into my golang program. The format is fixed in number of digit:
2006/01/02 15:04:05
I started to parse these dates with the time.Parse function
const dtFormat = "2006/01/02 15:04:05"
func ParseDate1(strdate string) (time.Time, error) {
return time.Parse(dtFormat, strdate)
}
but I had some performances issue with my program. Thus I tried to tune it by writting my own parsing function, taking into account that my format is kind of fixed:
func ParseDate2(strdate string) (time.Time, error) {
year, _ := strconv.Atoi(strdate[:4])
month, _ := strconv.Atoi(strdate[5:7])
day, _ := strconv.Atoi(strdate[8:10])
hour, _ := strconv.Atoi(strdate[11:13])
minute, _ := strconv.Atoi(strdate[14:16])
second, _ := strconv.Atoi(strdate[17:19])
return time.Date(year, time.Month(month), day, hour, minute, second, 0, time.UTC), nil
}
finally I did a benchmark on top of these 2 functions and got the following result:
BenchmarkParseDate1 5000000 343 ns/op
BenchmarkParseDate2 10000000 248 ns/op
This is a performance improvement by 27%. Is there a better way in terms of performances that could improve such datetime parsing ?