Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
Will array memory allocation be destroyed when function ends

Just wondering if garbage collector takes care of an array returned by function. Will this function cause memory leaks if called many times?

1.    myFun = () => {
2.       let data = []
3.       for (let i=1; i<5; i++){
4.           data.push(id: i, name: 'temp')
5.       }
6.       return data
7.    }
8.    
9.    let myData1 = myFun()
10.   let myData2 = myFun()
11.   let myData3 = myFun()

so it creates three new arrays. But what the one defined in row #2?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

But what the one defined in row #2?

That is the same exact array that is being returned. You aren't creating six arrays total (three inside, three outside) - you're creating three arrays total (three inside, which then get returned to the outside).

So, that array will remain un-garbage-collected as long as the returned expression remains referenceable. If your myData1, myData2, myData3 remain referenceable forever, none of the arrays will ever be garbage collected. If they become unreferenceable and nothing can continue using them, then they'll get garbage collected - for example, if you did

(() => {
    myFun = () => {
        let data = []
        for (let i = 1; i < 5; i++) {
            data.push(id: i, name: 'temp')
        }
        return data
    }

    let myData1 = myFun()
    let myData2 = myFun()
    let myData3 = myFun()
})();

Since myData1 etc aren't used again, and since the scope they're declared in ends, all arrays would then be shortly garbage collected.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda