From c1de95864d73a5465492829d7cb2dd422b19ac96 Mon Sep 17 00:00:00 2001 From: Albert Nigmatzianov Date: Mon, 19 Jun 2017 12:35:39 +0200 Subject: [PATCH] Prevent redundant type assertion in Get MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit There is no need to assert variables which already have appropriate type. name old time/op new time/op delta GetBool-4 554ns ± 3% 493ns ± 8% -10.86% (p=0.000 n=14+15) Get-4 484ns ± 4% 414ns ± 7% -14.37% (p=0.000 n=14+15) GetBoolFromMap-4 8.38ns ± 6% 7.83ns ± 7% -6.59% (p=0.000 n=15+15) name old alloc/op new alloc/op delta GetBool-4 65.0B ± 0% 64.0B ± 0% -1.54% (p=0.000 n=15+15) Get-4 64.0B ± 0% 64.0B ± 0% ~ (all equal) GetBoolFromMap-4 0.00B 0.00B ~ (all equal) name old allocs/op new allocs/op delta GetBool-4 5.00 ± 0% 4.00 ± 0% -20.00% (p=0.000 n=15+15) Get-4 5.00 ± 0% 4.00 ± 0% -20.00% (p=0.000 n=15+15) GetBoolFromMap-4 0.00 0.00 ~ (all equal) --- viper.go | 37 +++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/viper.go b/viper.go index 31b41a6..39a3c06 100644 --- a/viper.go +++ b/viper.go @@ -53,7 +53,7 @@ func init() { type remoteConfigFactory interface { Get(rp RemoteProvider) (io.Reader, error) Watch(rp RemoteProvider) (io.Reader, error) - WatchChannel(rp RemoteProvider)(<-chan *RemoteResponse, chan bool) + WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool) } // RemoteConfig is optional, see the remote package @@ -597,32 +597,33 @@ func (v *Viper) Get(key string) interface{} { return nil } - valType := val if v.typeByDefValue { // TODO(bep) this branch isn't covered by a single test. + valType := val path := strings.Split(lcaseKey, v.keyDelim) defVal := v.searchMap(v.defaults, path) if defVal != nil { valType = defVal } + + switch valType.(type) { + case bool: + return cast.ToBool(val) + case string: + return cast.ToString(val) + case int64, int32, int16, int8, int: + return cast.ToInt(val) + case float64, float32: + return cast.ToFloat64(val) + case time.Time: + return cast.ToTime(val) + case time.Duration: + return cast.ToDuration(val) + case []string: + return cast.ToStringSlice(val) + } } - switch valType.(type) { - case bool: - return cast.ToBool(val) - case string: - return cast.ToString(val) - case int64, int32, int16, int8, int: - return cast.ToInt(val) - case float64, float32: - return cast.ToFloat64(val) - case time.Time: - return cast.ToTime(val) - case time.Duration: - return cast.ToDuration(val) - case []string: - return cast.ToStringSlice(val) - } return val }