From bbed5559a59db54120dda79106f85f9ec0afb038 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Mon, 15 May 2023 10:09:44 +0200 Subject: [PATCH] Pull the 2006-01-02 layout to the top when checking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The current top 2 formats are, from some checks I've done, 2 dominant formats used in Hugo projects. Checking these first has a big effect: ```bash name old time/op new time/op delta CommonTimeLayouts-10 1.45µs ± 0% 0.33µs ± 1% -77.45% (p=0.029 n=4+4) name old alloc/op new alloc/op delta CommonTimeLayouts-10 1.55kB ± 0% 0.18kB ± 0% -88.14% (p=0.029 n=4+4) name old allocs/op new allocs/op delta CommonTimeLayouts-10 38.0 ± 0% 6.0 ± 0% -84.21% (p=0.029 n=4+4) ``` See https://github.com/gohugoio/hugo/issues/10942 --- cast_test.go | 11 +++++++++++ caste.go | 3 ++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cast_test.go b/cast_test.go index 016f8c2..6bea164 100644 --- a/cast_test.go +++ b/cast_test.go @@ -897,6 +897,17 @@ func BenchmarkTrimZeroDecimal(b *testing.B) { } } +func BenchmarkCommonTimeLayouts(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, commonLayout := range []string{"2019-04-29", "2017-05-30T00:00:00Z"} { + _, err := StringToDateInDefaultLocation(commonLayout, time.UTC) + if err != nil { + b.Fatal(err) + } + } + } +} + func TestIndirectPointers(t *testing.T) { c := qt.New(t) diff --git a/caste.go b/caste.go index bccf27a..d49bbf8 100644 --- a/caste.go +++ b/caste.go @@ -1406,6 +1406,8 @@ func (f timeFormat) hasTimezone() bool { var ( timeFormats = []timeFormat{ + // Keep common formats at the top. + {"2006-01-02", timeFormatNoTimezone}, {time.RFC3339, timeFormatNumericTimezone}, {"2006-01-02T15:04:05", timeFormatNoTimezone}, // iso8601 without timezone {time.RFC1123Z, timeFormatNumericTimezone}, @@ -1421,7 +1423,6 @@ var ( {time.UnixDate, timeFormatNamedTimezone}, {time.RubyDate, timeFormatNumericTimezone}, {"2006-01-02 15:04:05Z07:00", timeFormatNumericTimezone}, - {"2006-01-02", timeFormatNoTimezone}, {"02 Jan 2006", timeFormatNoTimezone}, {"2006-01-02 15:04:05 -07:00", timeFormatNumericTimezone}, {"2006-01-02 15:04:05 -0700", timeFormatNumericTimezone},