<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Gabriel Menezes da Silva</title>
    <description>The latest articles on Forem by Gabriel Menezes da Silva (@gabrielcodesolutions).</description>
    <link>https://forem.com/gabrielcodesolutions</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F221016%2Faaa2408f-e7b4-4bb2-a753-160e6dcb9ac5.jpeg</url>
      <title>Forem: Gabriel Menezes da Silva</title>
      <link>https://forem.com/gabrielcodesolutions</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/gabrielcodesolutions"/>
    <language>en</language>
    <item>
      <title>Melhorando a performance em Kotlin com concatenação de strings</title>
      <dc:creator>Gabriel Menezes da Silva</dc:creator>
      <pubDate>Tue, 07 Oct 2025 21:13:30 +0000</pubDate>
      <link>https://forem.com/gabrielcodesolutions/melhorando-a-performance-em-kotlin-com-concatenacao-de-strings-m44</link>
      <guid>https://forem.com/gabrielcodesolutions/melhorando-a-performance-em-kotlin-com-concatenacao-de-strings-m44</guid>
      <description>&lt;h2&gt;
  
  
  Contexto
&lt;/h2&gt;

&lt;p&gt;Trabalhei em um aplicativo mobile nativo para Android utilizado por uma empresa de logística. Esse app é usado por operadores para escanear etiquetas de pacotes e contêineres, a fim de realizar as etapas necessárias no sistema para classificá-los e ordená-los.&lt;/p&gt;

&lt;p&gt;Existe uma função responsável por receber a string, manipulá-las e enviar para o back-end a string correta para que ela seja processada.&lt;/p&gt;

&lt;p&gt;Essa função é o coração de todo o aplicativo — sem ela, o processo logístico não funcionaria. Portanto, qualquer melhoria nela é sempre muito bem-vinda.&lt;/p&gt;

&lt;p&gt;Neste artigo, será explicado quais melhorias foram feitas e os motivos por trás da implementação.&lt;/p&gt;

&lt;h2&gt;
  
  
  Qual foi a melhoria feita?
&lt;/h2&gt;

&lt;p&gt;Uma operação executada inúmeras vezes dentro dessa função é a concatenação de strings.&lt;/p&gt;

&lt;p&gt;Você pode estar se perguntando: por que melhorar a concatenação é importante?&lt;/p&gt;

&lt;p&gt;Dependendo de como ela é feita, você literalmente pode ter problemas de desempenho e uso excessivo de memória para obter o resultado final.&lt;/p&gt;

&lt;h2&gt;
  
  
  O problema
&lt;/h2&gt;

&lt;p&gt;Antes da melhoria, a concatenação das strings era feita da seguinte forma, usando o famoso operador +=, muito comum no dia a dia dos programadores Kotlin:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var result = ""
val iterations = 1000
for (i in 0 until iterations) {
    result += "Item $i "
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ok, mas qual é o problema de usar o +=?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A classe String é imutável, ou seja, a cada iteração uma nova instância de String é criada, e mais memória é alocada.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Em outras palavras, quanto maior o número de iterações, mais memória é usada e mais tempo é necessário para obter o resultado final!&lt;/p&gt;

&lt;h2&gt;
  
  
  A solução
&lt;/h2&gt;

&lt;p&gt;Usar o  &lt;strong&gt;StringBuilder&lt;/strong&gt; em vez do operador +=.&lt;/p&gt;

&lt;p&gt;Os motivos são simples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;1. StringBuilder é mutável, ou seja, nenhuma nova instância de string é criada a cada iteração.&lt;/li&gt;
&lt;li&gt;2. A mesma alocação de memória é usada durante todo o processo de concatenação.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;O código ficaria da seguinte forma:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val result = buildString {
    for (i in 0 until iterations) {
        append("Item $i ")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A função &lt;strong&gt;buildString&lt;/strong&gt; utiliza internamente o &lt;strong&gt;StringBuilder&lt;/strong&gt;.&lt;br&gt;
Para referência, veja a &lt;a href="https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/build-string.html" rel="noopener noreferrer"&gt;documentação&lt;/a&gt; oficial do Kotlin.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exemplo prático
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import kotlin.system.measureTimeMillis

fun main() {
    val iterations = 1000

    // Usando +=
    val timePlusEqual = measureTimeMillis {
        var result = ""
        for (i in 0 until iterations) {
            result += "Item $i "
        }
    }

    // Usando buildString (internamente usa StringBuilder)
    val timeBuildString = measureTimeMillis {
        val result = buildString {
            for (i in 0 until iterations) {
                append("Item $i ")
            }
        }
    }

    println("Tempo com +=: ${timePlusEqual}ms")
    println("Tempo com buildString: ${timeBuildString}ms")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;E o resultado será uma grande diferença:&lt;/p&gt;

&lt;p&gt;Tempo com +=: 21ms&lt;br&gt;&lt;br&gt;
Tempo com buildString: 0ms  &lt;/p&gt;

&lt;p&gt;Neste artigo foi mostrado apenas um exemplo simples, mas imagine isso em larga escala, com strings enormes — o tempo de execução e o consumo de memória aumentariam consideravelmente.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusão
&lt;/h2&gt;

&lt;p&gt;Muitas vezes pensamos que, para causar um grande impacto em um projeto, é preciso fazer algo gigantesco — como mudar toda a arquitetura do aplicativo.&lt;/p&gt;

&lt;p&gt;Mas isso não é verdade.&lt;br&gt;
Pequenas melhorias podem gerar um impacto enorme e entregar valor real aos clientes.&lt;br&gt;
Ter isso em mente traz uma sensação de conforto: saber que otimizações simples também fazem a diferença.&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>android</category>
      <category>programming</category>
    </item>
    <item>
      <title>Improving performance in Kotlin with string concatenation</title>
      <dc:creator>Gabriel Menezes da Silva</dc:creator>
      <pubDate>Wed, 01 Oct 2025 21:31:21 +0000</pubDate>
      <link>https://forem.com/gabrielcodesolutions/improving-function-with-string-concatenation-4882</link>
      <guid>https://forem.com/gabrielcodesolutions/improving-function-with-string-concatenation-4882</guid>
      <description>&lt;h2&gt;
  
  
  Context
&lt;/h2&gt;

&lt;p&gt;I worked in a native android mobile application used by a logistic company. This app is used by operators to scan the labels of packages/containers in order to do the steps necessary in the system to sort them.&lt;/p&gt;

&lt;p&gt;There's a function where it gets the label string/bytes, manipulates it and delivers to the back-end the correct string so they can process it.&lt;/p&gt;

&lt;p&gt;This function is the heartbeat of the whole application, without it, the logistics will not work, so every improvement in it, it's always welcomed.&lt;/p&gt;

&lt;p&gt;In this article, It will be explained which improvements were done and the reasons why they were implemented.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which improvement was done?
&lt;/h2&gt;

&lt;p&gt;A operation that is done numerous times in this function is the concatenation.&lt;/p&gt;

&lt;p&gt;You might be asking, but why improving the concatenation is important? &lt;strong&gt;Depending on the concatenation that is being done, you literally can have problems of memory and time to get the result.&lt;/strong&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Problem
&lt;/h2&gt;

&lt;p&gt;So before the improvement, the concatenation of the strings was being done like described in the code below, using the famous &lt;code&gt;+=&lt;/code&gt; operator, very commonly used in the daily basis:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; var result = ""
   val iterations = 1000
   for (i in 0 until iterations) {
       result += "Item $i "
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ok, but what's the problem of using it?:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;String is a immutable object, that is, in every iteration a new instance of String is created, more memory is allocated.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That is, the more you increase the number of iterations, more memory is allocated and more time will be taken to get the result!! &lt;/p&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;Use &lt;strong&gt;StringBuilder&lt;/strong&gt; instead of using the operator &lt;code&gt;+=&lt;/code&gt;. The reasons why will be described below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;StringBuilder is a mutable object, that is, no new instance of string is created in every iteration.&lt;/li&gt;
&lt;li&gt;The same memory allocation is used for all the concatenation process, all the iteration.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following code shows how this could be implemented:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  val result = buildString {
            for (i in 0 until iterations) {
                append("Item $i ")
            }
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;buildString&lt;/strong&gt; uses &lt;strong&gt;StringBuilder&lt;/strong&gt; under the hood. For reference checkout this kotlin doc &lt;a href="https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/build-string.html" rel="noopener noreferrer"&gt;link&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you run the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */
import kotlin.system.measureTimeMillis
fun main() {
  val iterations = 1000


    val timePlusEqual = measureTimeMillis {
        var result = ""
        for (i in 0 until iterations) {
            result += "Item $i "
        }
    }

    // StringBuilder
    // Kotlin is under the hood using a StringBuilder, 
    val timeBuildString = measureTimeMillis {
        val result = buildString {
            for (i in 0 until iterations) {
                append("Item $i ")
            }
        }
    }

    println("Time with +=: ${timePlusEqual}ms")
    println("Time with buildString: ${timeBuildString}ms")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You'll get this BIG difference:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Time with +=: 21ms
Time with buildString: 0ms
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this article I'm just writing a simple example, but imagine this in a big scale, with very big strings, this time difference and memory will increase.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Sometimes we think that to create huge impact in a project, It's necessary to do big things like changing the architecture of the whole app. &lt;br&gt;
That's not true, simple things can bring huge impact and deliver real good value for the clients. It's necessary to have that in our minds,  It creates a feeling of comfort.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>mobile</category>
      <category>kotlin</category>
      <category>android</category>
    </item>
  </channel>
</rss>
