3

Doing some profiling, it seems my bottleneck is the Kotlin kotlin.CharSequence.split() extension function.

My code just does something like this:

val delimiter = '\t'
val line = "example\tline"
val parts = line.split(delimiter)

As you might notice, parts is a List<String>.

I wanted to benchmark using Java's split directly, which returns a String[] and might be more efficient.

How can I call Java's String::split(String) directly from Kotlin source?

2 Answers 2

5

You can cast a kotlin.String to a java.lang.String then use the java.lang.String#split since kotlin.String will be mapped to java.lang.String , but you'll get a warnings. for example:

//                               v--- PLATFORM_CLASS_MAPPED_TO_KOTLIN warnings
val parts: Array<String> = (line as java.lang.String).split("\t")

You also can use the java.util.regex.Pattern#split instead, as @Renato metioned it will slower than java.lang.String#split in some situations. for example:

val parts: Array<String> = Pattern.compile("\t").split(line, 0)

But be careful, kotlin.String#split's behavior is different with java.lang.String#split , for example:

val line: String = "example\tline\t"

//   v--- ["example", "line"]
val parts1: Array<String> = Pattern.compile("\t").split(line, 0)

//   v--- ["example", "line", ""]
val parts2 = line.split("\t".toRegex())
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, that helps a lot!
In case anyone uses this, you can suppress the warning with @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
In case anyone wanted to know: Java split is much faster than Kotlin's if you use it millions of times (I was splitting over a million lines and after changing to Java split, it did the job almost twice as fast). The Pattern solution is much slower even than the Kotlin's split.
It's not off-topic. The only reason you would do this is for performance, so it's good to know it pays off.
@Renato I admit that Pattern#split is an optional way, I'll fix my answer. thanks for your feedback, sir. How about it now?
|
2

You can do this:

(line as java.lang.String).split(delimiter)

But it's not recommended to not use the kotlin.String as the compiler might tell you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.