You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Memory management in JavaScript is performed automatically and invisibly to us. We create primitives, objects, functions... All that takes memory.
3
+
O gerenciamento de memória em JavaScript é realizado automaticamente e de forma invisível para nós. Criamos primitivos, objetos, funções... Tudo isso ocupa memória.
4
4
5
-
What happens when something is not needed any more? How does the JavaScript engine discover it and clean it up?
5
+
O que acontece quando algo não é mais necessário? Como o motor JavaScript descobre isso e limpa a memória?
6
6
7
-
## Reachability
7
+
## Alcançabilidade
8
8
9
-
The main concept of memory management in JavaScript is *reachability*.
9
+
O conceito principal do gerenciamento de memória em JavaScript é *alcançabilidade*.
10
10
11
-
Simply put, "reachable" values are those that are accessible or usable somehow. They are guaranteed to be stored in memory.
11
+
Simplificando, valores "alcançáveis" são aqueles que são acessíveis ou utilizáveis de alguma forma. Eles têm garantia de permanecerem armazenados na memória.
12
12
13
-
1.There's a base set of inherently reachable values, that cannot be deleted for obvious reasons.
13
+
1.Existe um conjunto base de valores inerentemente alcançáveis, que não podem ser deletados por razões óbvias.
14
14
15
-
For instance:
15
+
Por exemplo:
16
16
17
-
-The currently executing function, its local variables and parameters.
18
-
-Other functions on the current chain of nested calls, their local variables and parameters.
19
-
-Global variables.
20
-
- (there are some other, internal ones as well)
17
+
-A função atualmente em execução, suas variáveis locais e parâmetros.
18
+
-Outras funções na cadeia atual de chamadas aninhadas, suas variáveis locais e parâmetros.
19
+
-Variáveis globais.
20
+
- (existem algumas outras, internas também)
21
21
22
-
These values are called *roots*.
22
+
Esses valores são chamados de *raízes*.
23
23
24
-
2.Any other value is considered reachable if it's reachable from a root by a reference or by a chain of references.
24
+
2.Qualquer outro valor é considerado alcançável se for alcançável a partir de uma raiz por uma referência ou por uma cadeia de referências.
25
25
26
-
For instance, if there's an object in a global variable, and that object has a property referencing another object, *that* object is considered reachable. And those that it references are also reachable. Detailed examples to follow.
26
+
Por exemplo, se existe um objeto em uma variável global, e esse objeto tem uma propriedade referenciando outro objeto, *esse* objeto é considerado alcançável. E aqueles que ele referencia também são alcançáveis. Exemplos detalhados a seguir.
27
27
28
-
There's a background process in the JavaScript engine that is called [garbage collector](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)). It monitors all objects and removes those that have become unreachable.
28
+
Existe um processo em segundo plano no motor JavaScript que é chamado de [coletor de lixo](https://pt.wikipedia.org/wiki/Coletor_de_lixo_(inform%C3%A1tica)). Ele monitora todos os objetos e remove aqueles que se tornaram inalcançáveis.
29
29
30
-
## A simple example
30
+
## Um exemplo simples
31
31
32
-
Here's the simplest example:
32
+
Aqui está o exemplo mais simples:
33
33
34
34
```js
35
-
// user has a reference to the object
35
+
// user tem uma referência ao objeto
36
36
let user = {
37
37
name:"John"
38
38
};
39
39
```
40
40
41
41

42
42
43
-
Here the arrow depicts an object reference. The global variable `"user"`references the object`{name: "John"}` (we'll call it John for brevity). The `"name"`property of John stores a primitive, so it's painted inside the object.
43
+
Aqui a seta representa uma referência a um objeto. A variável global `"user"`referencia o objeto`{name: "John"}` (vamos chamá-lo de John por brevidade). A propriedade `"name"`de John armazena um primitivo, então está pintada dentro do objeto.
44
44
45
-
If the value of`user`is overwritten, the reference is lost:
45
+
Se o valor de`user`for sobrescrito, a referência é perdida:
46
46
47
47
```js
48
48
user =null;
49
49
```
50
50
51
51

52
52
53
-
Now John becomes unreachable. There's no way to access it, no references to it. Garbage collector will junk the data and free the memory.
53
+
Agora John se torna inalcançável. Não há como acessá-lo, não existem referências a ele. O coletor de lixo descartará os dados e liberará a memória.
54
54
55
-
## Two references
55
+
## Duas referências
56
56
57
-
Now let's imagine we copied the reference from`user`to`admin`:
57
+
Agora vamos imaginar que copiamos a referência de`user`para`admin`:
58
58
59
59
```js
60
-
// user has a reference to the object
60
+
// user tem uma referência ao objeto
61
61
let user = {
62
62
name:"John"
63
63
};
@@ -69,16 +69,16 @@ let admin = user;
69
69
70
70

71
71
72
-
Now if we do the same:
72
+
Agora se fizermos o mesmo:
73
73
```js
74
74
user =null;
75
75
```
76
76
77
-
...Then the object is still reachable via `admin`global variable, so it must stay in memory. If we overwrite `admin`too, then it can be removed.
77
+
...Então o objeto ainda é alcançável via a variável global `admin`, então ele deve permanecer na memória. Se sobrescrevermos `admin`também, então ele pode ser removido.
78
78
79
-
## Interlinked objects
79
+
## Objetos interligados
80
80
81
-
Now a more complex example. The family:
81
+
Agora um exemplo mais complexo. A família:
82
82
83
83
```js
84
84
functionmarry(man, woman) {
@@ -98,15 +98,15 @@ let family = marry({
98
98
});
99
99
```
100
100
101
-
Function `marry` "marries" two objects by giving them references to each other and returns a new object that contains them both.
101
+
A função `marry` "casa" dois objetos dando a eles referências um ao outro e retorna um novo objeto que contém ambos.
It's not enough to delete only one of these two references, because all objects would still be reachable.
118
+
Não é suficiente deletar apenas uma dessas duas referências, porque todos os objetos ainda seriam alcançáveis.
119
119
120
-
But if we delete both, then we can see that John has no incoming reference any more:
120
+
Mas se deletarmos ambas, então podemos ver que John não tem mais nenhuma referência de entrada:
121
121
122
122

123
123
124
-
Outgoing references do not matter. Only incoming ones can make an object reachable. So, John is now unreachable and will be removed from the memory with all its data that also became unaccessible.
124
+
Referências de saída não importam. Apenas as de entrada podem tornar um objeto alcançável. Então, John agora é inalcançável e será removido da memória com todos os seus dados que também se tornaram inacessíveis.
125
125
126
-
After garbage collection:
126
+
Após a coleta de lixo:
127
127
128
128

129
129
130
-
## Unreachable island
130
+
## Ilha inalcançável
131
131
132
-
It is possible that the whole island of interlinked objects becomes unreachable and is removed from the memory.
132
+
É possível que toda uma ilha de objetos interligados se torne inalcançável e seja removida da memória.
133
133
134
-
The source object is the same as above. Then:
134
+
O objeto fonte é o mesmo de antes. Então:
135
135
136
136
```js
137
137
family =null;
138
138
```
139
139
140
-
The in-memory picture becomes:
140
+
A imagem na memória se torna:
141
141
142
142

143
143
144
-
This example demonstrates how important the concept of reachability is.
144
+
Este exemplo demonstra quão importante é o conceito de alcançabilidade.
145
145
146
-
It's obvious that John and Ann are still linked, both have incoming references. But that's not enough.
146
+
É óbvio que John e Ann ainda estão ligados, ambos têm referências de entrada. Mas isso não é suficiente.
147
147
148
-
The former `"family"`object has been unlinked from the root, there's no reference to it any more, so the whole island becomes unreachable and will be removed.
148
+
O antigo objeto `"family"`foi desligado da raiz, não há mais referência a ele, então toda a ilha se torna inalcançável e será removida.
149
149
150
-
## Internal algorithms
150
+
## Algoritmos internos
151
151
152
-
The basic garbage collection algorithm is called "mark-and-sweep".
152
+
O algoritmo básico de coleta de lixo é chamado de "marcar-e-varrer" (*mark-and-sweep*).
153
153
154
-
The following "garbage collection" steps are regularly performed:
154
+
Os seguintes passos de "coleta de lixo" são realizados regularmente:
155
155
156
-
-The garbage collector takes roots and "marks" (remembers) them.
157
-
-Then it visits and "marks" all references from them.
158
-
-Then it visits marked objects and marks *their* references. All visited objects are remembered, so as not to visit the same object twice in the future.
159
-
- ...And so on until every reachable (from the roots) references are visited.
160
-
-All objects except marked ones are removed.
156
+
-O coletor de lixo pega as raízes e as "marca" (lembra delas).
157
+
-Então ele visita e "marca" todas as referências a partir delas.
158
+
-Então ele visita os objetos marcados e marca *suas* referências. Todos os objetos visitados são lembrados, para não visitar o mesmo objeto duas vezes no futuro.
159
+
- ...E assim por diante até que todas as referências alcançáveis (a partir das raízes) sejam visitadas.
160
+
-Todos os objetos exceto os marcados são removidos.
161
161
162
-
For instance, let our object structure look like this:
162
+
Por exemplo, vamos supor que nossa estrutura de objetos se parece com isso:
163
163
164
164

165
165
166
-
We can clearly see an "unreachable island" to the right side. Now let's see how "mark-and-sweep" garbage collector deals with it.
166
+
Podemos ver claramente uma "ilha inalcançável" no lado direito. Agora vamos ver como o coletor de lixo "marcar-e-varrer" lida com isso.
167
167
168
-
The first step marks the roots:
168
+
O primeiro passo marca as raízes:
169
169
170
170

171
171
172
-
Then we follow their references and mark referenced objects:
172
+
Então seguimos suas referências e marcamos os objetos referenciados:
173
173
174
174

175
175
176
-
...And continue to follow further references, while possible:
176
+
...E continuamos a seguir mais referências, enquanto possível:
177
177
178
178

179
179
180
-
Now the objects that could not be visited in the process are considered unreachable and will be removed:
180
+
Agora os objetos que não puderam ser visitados no processo são considerados inalcançáveis e serão removidos:
181
181
182
182

183
183
184
-
We can also imagine the process as spilling a huge bucket of paint from the roots, that flows through all references and marks all reachable objects. The unmarked ones are then removed.
184
+
Também podemos imaginar o processo como derramar um enorme balde de tinta a partir das raízes, que flui através de todas as referências e marca todos os objetos alcançáveis. Os não marcados são então removidos.
185
185
186
-
That's the concept of how garbage collection works. JavaScript engines apply many optimizations to make it run faster and not introduce any delays into the code execution.
186
+
Esse é o conceito de como a coleta de lixo funciona. Os motores JavaScript aplicam muitas otimizações para fazê-la rodar mais rápido e não introduzir atrasos na execução do código.
187
187
188
-
Some of the optimizations:
188
+
Algumas das otimizações:
189
189
190
-
-**Generational collection** -- objects are split into two sets: "new ones" and "old ones". In typical code, many objects have a short life span: they appear, do their job and die fast, so it makes sense to track new objects and clear the memory from them if that's the case. Those that survive for long enough, become "old" and are examined less often.
191
-
-**Incremental collection** -- if there are many objects, and we try to walk and mark the whole object set at once, it may take some time and introduce visible delays in the execution. So the engine splits the whole set of existing objects into multiple parts. And then clear these parts one after another. There are many small garbage collections instead of a total one. That requires some extra bookkeeping between them to track changes, but we get many tiny delays instead of a big one.
192
-
-**Idle-time collection** -- the garbage collector tries to run only while the CPU is idle, to reduce the possible effect on the execution.
190
+
-**Coleta geracional** -- objetos são divididos em dois conjuntos: "novos" e "velhos". Em código típico, muitos objetos têm uma vida curta: eles aparecem, fazem seu trabalho e morrem rápido, então faz sentido rastrear objetos novos e limpar a memória deles se for o caso. Aqueles que sobrevivem por tempo suficiente, se tornam "velhos" e são examinados com menos frequência.
191
+
-**Coleta incremental** -- se há muitos objetos, e tentamos percorrer e marcar todo o conjunto de objetos de uma vez, isso pode levar algum tempo e introduzir atrasos visíveis na execução. Então o motor divide todo o conjunto de objetos existentes em múltiplas partes. E então limpa essas partes uma após a outra. Há muitas pequenas coletas de lixo ao invés de uma total. Isso requer alguma contabilidade extra entre elas para rastrear mudanças, mas temos muitos pequenos atrasos ao invés de um grande.
192
+
-**Coleta em tempo ocioso** -- o coletor de lixo tenta executar apenas enquanto a CPU está ociosa, para reduzir o possível efeito na execução.
193
193
194
-
There exist other optimizations and flavours of garbage collection algorithms. As much as I'd like to describe them here, I have to hold off, because different engines implement different tweaks and techniques. And, what's even more important, things change as engines develop, so studying deeper "in advance", without a real need is probably not worth that. Unless, of course, it is a matter of pure interest, then there will be some links for you below.
194
+
Existem outras otimizações e variantes de algoritmos de coleta de lixo. Por mais que eu gostaria de descrevê-las aqui, tenho que me conter, porque diferentes motores implementam diferentes ajustes e técnicas. E, o que é ainda mais importante, as coisas mudam conforme os motores se desenvolvem, então estudar mais a fundo "antecipadamente", sem uma necessidade real, provavelmente não vale a pena. A menos, é claro, que seja uma questão de puro interesse, então haverá alguns links para você abaixo.
195
195
196
-
## Summary
196
+
## Resumo
197
197
198
-
The main things to know:
198
+
As principais coisas a saber:
199
199
200
-
-Garbage collection is performed automatically. We cannot force or prevent it.
201
-
-Objects are retained in memory while they are reachable.
202
-
-Being referenced is not the same as being reachable (from a root): a pack of interlinked objects can become unreachable as a whole, as we've seen in the example above.
200
+
-A coleta de lixo é realizada automaticamente. Não podemos forçá-la ou preveni-la.
201
+
-Objetos são mantidos na memória enquanto são alcançáveis.
202
+
-Ser referenciado não é o mesmo que ser alcançável (a partir de uma raiz): um conjunto de objetos interligados pode se tornar inalcançável como um todo, como vimos no exemplo acima.
203
203
204
-
Modern engines implement advanced algorithms of garbage collection.
204
+
Motores modernos implementam algoritmos avançados de coleta de lixo.
205
205
206
-
A general book "The Garbage Collection Handbook: The Art of Automatic Memory Management" (R. Jones et al) covers some of them.
206
+
Um livro geral "The Garbage Collection Handbook: The Art of Automatic Memory Management" (R. Jones et al) cobre alguns deles.
207
207
208
-
If you are familiar with low-level programming, more detailed information about V8's garbage collector is in the article[A tour of V8: Garbage Collection](https://jayconrod.com/posts/55/a-tour-of-v8-garbage-collection).
208
+
Se você está familiarizado com programação de baixo nível, informações mais detalhadas sobre o coletor de lixo do V8 estão no artigo[A tour of V8: Garbage Collection](https://jayconrod.com/posts/55/a-tour-of-v8-garbage-collection).
209
209
210
-
The [V8 blog](https://v8.dev/)also publishes articles about changes in memory management from time to time. Naturally, to learn more about garbage collection, you'd better prepare by learning about V8 internals in general and read the blog of[Vyacheslav Egorov](https://mrale.ph)who worked as one of the V8 engineers. I'm saying: "V8", because it is best covered by articles on the internet. For other engines, many approaches are similar, but garbage collection differs in many aspects.
210
+
O [blog do V8](https://v8.dev/)também publica artigos sobre mudanças no gerenciamento de memória de tempos em tempos. Naturalmente, para aprender mais sobre coleta de lixo, é melhor se preparar aprendendo sobre os internos do V8 em geral e ler o blog de[Vyacheslav Egorov](https://mrale.ph)que trabalhou como um dos engenheiros do V8. Estou dizendo: "V8", porque é o melhor coberto por artigos na internet. Para outros motores, muitas abordagens são similares, mas a coleta de lixo difere em muitos aspectos.
211
211
212
-
In-depth knowledge of engines is good when you need low-level optimizations. It would be wise to plan that as the next step after you're familiar with the language.
212
+
Conhecimento profundo dos motores é bom quando você precisa de otimizações de baixo nível. Seria sábio planejar isso como o próximo passo depois que você estiver familiarizado com a linguagem.
0 commit comments