From 511f94e3412315b7459c1c3524a22ed6cebcd59a Mon Sep 17 00:00:00 2001 From: chanxuehong Date: Wed, 13 May 2020 21:16:52 +0800 Subject: [PATCH] performance improvement for parseDateTime --- AUTHORS | 1 + utils.go | 14 ++++---------- utils_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/AUTHORS b/AUTHORS index 98cb1e66f..e24231d81 100644 --- a/AUTHORS +++ b/AUTHORS @@ -90,6 +90,7 @@ Vladimir Kovpak Xiangyu Hu Xiaobing Jiang Xiuming Chen +Xuehong Chan Zhenye Xie Zhixin Wen diff --git a/utils.go b/utils.go index 9552e80b5..154ecc337 100644 --- a/utils.go +++ b/utils.go @@ -113,20 +113,14 @@ func parseDateTime(str string, loc *time.Location) (t time.Time, err error) { if str == base[:len(str)] { return } - t, err = time.Parse(timeFormat[:len(str)], str) + if loc == time.UTC { + return time.Parse(timeFormat[:len(str)], str) + } + return time.ParseInLocation(timeFormat[:len(str)], str, loc) default: err = fmt.Errorf("invalid time string: %s", str) return } - - // Adjust location - if err == nil && loc != time.UTC { - y, mo, d := t.Date() - h, mi, s := t.Clock() - t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil - } - - return } func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) { diff --git a/utils_test.go b/utils_test.go index 10a60c2d0..ab29cad78 100644 --- a/utils_test.go +++ b/utils_test.go @@ -14,6 +14,7 @@ import ( "database/sql/driver" "encoding/binary" "testing" + "time" ) func TestLengthEncodedInteger(t *testing.T) { @@ -291,3 +292,45 @@ func TestIsolationLevelMapping(t *testing.T) { t.Fatalf("Expected error to be %q, got %q", expectedErr, err) } } + +func TestParseDateTime(t *testing.T) { + // UTC loc + { + str := "2020-05-13 21:30:45" + t1, err := parseDateTime(str, time.UTC) + if err != nil { + t.Error(err) + return + } + t2 := time.Date(2020, 5, 13, + 21, 30, 45, 0, time.UTC) + if !t1.Equal(t2) { + t.Errorf("want equal, have: %v, want: %v", t1, t2) + return + } + } + // non-UTC loc + { + str := "2020-05-13 21:30:45" + loc := time.FixedZone("test", 8*60*60) + t1, err := parseDateTime(str, loc) + if err != nil { + t.Error(err) + return + } + t2 := time.Date(2020, 5, 13, + 21, 30, 45, 0, loc) + if !t1.Equal(t2) { + t.Errorf("want equal, have: %v, want: %v", t1, t2) + return + } + } +} + +func BenchmarkParseDateTime(b *testing.B) { + str := "2020-05-13 21:30:45" + loc := time.FixedZone("test", 8*60*60) + for i := 0; i < b.N; i++ { + _, _ = parseDateTime(str, loc) + } +}