0
0
Kotlinprogramming~5 mins

StringBuilder for performance in Kotlin

Choose your learning style9 modes available
Introduction

StringBuilder helps you build text quickly without making many copies. It makes your program faster when joining many pieces of text.

When you need to join many words or sentences together.
When you want to create a long message step by step.
When you want to avoid slow text joining in loops.
When you want to build text efficiently in games or apps.
When you want to save memory by not creating many temporary strings.
Syntax
Kotlin
val sb = StringBuilder()
sb.append("Hello")
sb.append(" World")
val result = sb.toString()

Use append() to add text to the builder.

Call toString() to get the final combined text.

Examples
This adds three parts and prints "Hi, there!".
Kotlin
val sb = StringBuilder()
sb.append("Hi")
sb.append(", ")
sb.append("there!")
println(sb.toString())
You can start with some text inside the builder.
Kotlin
val sb = StringBuilder("Start")
sb.append(" and continue")
println(sb.toString())
Use StringBuilder in loops to add numbers efficiently.
Kotlin
val sb = StringBuilder()
for (i in 1..3) {
    sb.append(i).append(", ")
}
println(sb.toString())
Sample Program

This program builds a list of numbers separated by commas using StringBuilder for better speed.

Kotlin
fun main() {
    val sb = StringBuilder()
    sb.append("Numbers: ")
    for (i in 1..5) {
        sb.append(i)
        if (i < 5) sb.append(", ")
    }
    println(sb.toString())
}
OutputSuccess
Important Notes

Using + to join strings creates new copies each time, which is slower.

StringBuilder is mutable, so it changes the same object instead of making new ones.

Always call toString() at the end to get the combined text.

Summary

StringBuilder helps join text faster by avoiding many copies.

Use append() to add pieces of text.

Call toString() to get the final string.