https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Danish Ansari

09/24/2021, 7:27 AM
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

Joffrey

09/24/2021, 7:29 AM
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

Roukanken

09/24/2021, 7:31 AM
(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

Danish Ansari

09/24/2021, 7:32 AM
@Joffrey @Roukanken so it's safe to create as many extensions as I want, right?
Since they are just top level static functions
j

Joffrey

09/24/2021, 7:39 AM
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

Roukanken

09/24/2021, 7:45 AM
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

Danish Ansari

09/24/2021, 7:50 AM
Ok thanks a lot @Joffrey and @Roukanken