Skip to content

Commit cdf17ef

Browse files
Improve string operations in tokenize
By avoiding unnecessary string operations it improved execute time. Previously `findWords` took 258ms to execute with this update it took 33ms
1 parent e384623 commit cdf17ef

1 file changed

Lines changed: 10 additions & 20 deletions

File tree

src/main/kotlin/cc/wordview/gengolex/languages/japanese/JapaneseTokenizer.kt

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,21 @@ object JapaneseTokenizer : Tokenizer {
1515
private val kanjiPattern: Pattern = Pattern.compile("[一-龯]")
1616

1717
override fun tokenize(words: List<String>): ArrayList<Word> {
18-
val wordsByChars = words.joinToString().replace("", "").replace("", "").split("")
19-
val joinedWordsString = wordsByChars.joinToString("")
18+
val input = words.joinToString()
19+
.replace("", "")
20+
.replace("", "")
2021

21-
val wordsFound = ArrayList<Word>()
22-
var charsToSkipNext = 0
22+
val chars = input.toCharArray()
2323

24+
val wordsFound = ArrayList<Word>()
2425
var i = 0
2526

26-
while (i < wordsByChars.size) {
27-
if (charsToSkipNext > 0) {
28-
charsToSkipNext--
29-
continue
30-
}
31-
32-
val char = wordsByChars[i]
33-
34-
val currentWordsString =
35-
wordsFound.fold(joinedWordsString) { acc, foundWord -> acc.replace(foundWord.word, "") }
36-
37-
tokenizeKanji(char, currentWordsString)?.let {
27+
while (i < chars.size) {
28+
val char = chars[i].toString()
29+
tokenizeKanji(char, input.substring(i))?.let {
3830
wordsFound.add(it)
39-
charsToSkipNext = it.word.length - 1
40-
}
41-
42-
i++
31+
i += it.word.length // Skip characters based on the word's length
32+
} ?: i++
4333
}
4434

4535
return wordsFound

0 commit comments

Comments
 (0)