From ddc7bb9064042a0d5da9546eaf6ff888dca63f0c Mon Sep 17 00:00:00 2001 From: Junegunn Choi Date: Sun, 14 Aug 2016 01:53:06 +0900 Subject: [perf] Optimize AWK-style tokenizer for --nth Approx. 50% less memory footprint and 40% improvement in query time --- src/util/chars.go | 7 +++++++ src/util/chars_test.go | 21 +++++++++++++++++++++ src/util/util.go | 24 ------------------------ src/util/util_test.go | 20 -------------------- 4 files changed, 28 insertions(+), 44 deletions(-) (limited to 'src/util') diff --git a/src/util/chars.go b/src/util/chars.go index 25a15ddd..6034ee53 100644 --- a/src/util/chars.go +++ b/src/util/chars.go @@ -111,3 +111,10 @@ func (chars *Chars) ToRunes() []rune { } return runes } + +func (chars *Chars) Slice(b int, e int) Chars { + if chars.runes != nil { + return Chars{runes: chars.runes[b:e]} + } + return Chars{bytes: chars.bytes[b:e]} +} diff --git a/src/util/chars_test.go b/src/util/chars_test.go index e42cfb7c..2cb6fc76 100644 --- a/src/util/chars_test.go +++ b/src/util/chars_test.go @@ -34,3 +34,24 @@ func TestCharsToString(t *testing.T) { t.Error() } } + +func TestTrimLength(t *testing.T) { + check := func(str string, exp int) { + chars := ToChars([]byte(str)) + trimmed := chars.TrimLength() + if trimmed != exp { + t.Errorf("Invalid TrimLength result for '%s': %d (expected %d)", + str, trimmed, exp) + } + } + check("hello", 5) + check("hello ", 5) + check("hello ", 5) + check(" hello", 5) + check(" hello", 5) + check(" hello ", 5) + check(" hello ", 5) + check("h o", 5) + check(" h o ", 5) + check(" ", 0) +} diff --git a/src/util/util.go b/src/util/util.go index 90cc28b4..a95340e7 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -83,30 +83,6 @@ func IsTty() bool { return int(C.isatty(C.int(os.Stdin.Fd()))) != 0 } -// TrimLen returns the length of trimmed rune array -func TrimLen(runes []rune) int { - var i int - for i = len(runes) - 1; i >= 0; i-- { - char := runes[i] - if char != ' ' && char != '\t' { - break - } - } - // Completely empty - if i < 0 { - return 0 - } - - var j int - for j = 0; j < len(runes); j++ { - char := runes[j] - if char != ' ' && char != '\t' { - break - } - } - return i - j + 1 -} - // ExecCommand executes the given command with $SHELL func ExecCommand(command string) *exec.Cmd { shell := os.Getenv("SHELL") diff --git a/src/util/util_test.go b/src/util/util_test.go index 8aeaeac5..06cfd4f2 100644 --- a/src/util/util_test.go +++ b/src/util/util_test.go @@ -20,23 +20,3 @@ func TestContrain(t *testing.T) { t.Error("Expected", 3) } } - -func TestTrimLen(t *testing.T) { - check := func(str string, exp int) { - trimmed := TrimLen([]rune(str)) - if trimmed != exp { - t.Errorf("Invalid TrimLen result for '%s': %d (expected %d)", - str, trimmed, exp) - } - } - check("hello", 5) - check("hello ", 5) - check("hello ", 5) - check(" hello", 5) - check(" hello", 5) - check(" hello ", 5) - check(" hello ", 5) - check("h o", 5) - check(" h o ", 5) - check(" ", 0) -} -- cgit v1.2.3