Reputation: 13690
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?
Upvotes: 3
Views: 1924
Reputation: 30686
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())
Upvotes: 5
Reputation: 81929
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.
Upvotes: 2