Quick question regarding extension functions: Let'...
# getting-started
d
Quick question regarding extension functions: Let's say if I add 1000 extensions functions in a
String
(just a scenario), so does that have any impact on performance? Just want to understand how exactly extension functions work and if there's any cost (or disadvantage) in using it that I should be aware of.
j
Extension functions are just like regular functions. Top-level extensions are static functions, member extensions are regular methods. Adding a lot of functions will just increase the bytecode size
r
(top-level) Extensions functions can be basically considered static methods The costs the usual Java's pattern of
StringUtils
class with 1000 static methods, each of which takes a string as first parameters will be similar
d
@Joffrey @Roukanken so it's safe to create as many extensions as I want, right?
Since they are just top level static functions
j
Yes, it's as safe as just declaring a lot of regular static functions or methods
👍 1
Bytecode size should not be too much of a performance problem in itself, apart from download time of your library or application, but 1000 methods should not even be noticeable. IIRC there is a method count limit on Android, so if that is your target platform you might have problems
👍 1
r
Yes, there is basically no performance cost to them If we're talking about disadvantages (as you mentioned too), there is a small one when you are working with inheritance though: since they are static function, they get resolved depending upon static type of the variable, and not runtime type as methods get resolved
Copy code
open class A {
    open fun doSmthElse() = println("A.doSmthElse")
}

class B : A() {
	override fun doSmthElse() = println("B.doSmthElse")
}

fun A.doSmth() = println("A.doSmth")
fun B.doSmth() = println("B.doSmth")

fun main() {
    val x: A = B()  // this line is at fault: x's type is A, but it stores instance of type B
    
    x.doSmth()
    x.doSmthElse()
}
this will print
Copy code
A.doSmth
B.doSmthElse
But that's not really fault of extension funcs, but the difference between methods and top-level functions
👍 1
d
Ok thanks a lot @Joffrey and @Roukanken