È il modo in cui le varie singole operazioni bytecode ricevono il loro input e come forniscono il loro output.
Ad esempio, considerare l'operazione iadd
, che aggiunge due int
s insieme. Per usarlo, si preme due valori nello stack e quindi utilizzarlo:
iload_0 # Push the value from local variable 0 onto the stack
iload_1 # Push the value from local variable 1 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
Ora il valore in cima alla pila è la somma di queste due variabili locali. L'operazione successiva potrebbe prendere quel valore di stack superiore e memorizzarlo da qualche parte, oppure potremmo spingere un altro valore nello stack per fare qualcos'altro.
Supponiamo di voler aggiungere tre valori insieme.Lo stack lo rende così semplice:
iload_0 # Push the value from local variable 0 onto the stack
iload_1 # Push the value from local variable 1 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
iload_2 # Push the value from local variable 2 onto the stack
iadd # Pops those off the stack, adds them, and pushes the result
Ora il valore superiore dello stack è il risultato dell'aggiunta di quelle tre variabili locali. sguardo
Let in quel secondo esempio più in dettaglio:
avanti assumeremo:
- La pila è vuota per iniziare con (che non è quasi mai effettivamente vero, ma noi non lo fanno cura ciò che è su di esso prima di iniziare)
- variabile locale 0 contiene
27
- variabile locale 1 contiene
10
- variabile locale 2 contiene
5
Così inizialmente:
+-------+
| stack |
+-------+
+-------+
Poi facciamo
iload_0 # Push the value from local variable 0 onto the stack
Ora abbiamo
+-------+
| stack |
+-------+
| 27 |
+-------+
Avanti
012.351.641.061.
iload_1 # Push the value from local variable 1 onto the stack
+-------+
| stack |
+-------+
| 10 |
| 27 |
+-------+
Ora facciamo l'aggiunta:
iadd # Pops those off the stack, adds them, and pushes the result
It "pop" il 10
e 27
dallo stack, li somma, e spinge il risultato (37
). Ora abbiamo:
+-------+
| stack |
+-------+
| 37 |
+-------+
Tempo per il nostro terzo int
:
iload_2 # Push the value from local variable 2 onto the stack
+-------+
| stack |
+-------+
| 5 |
| 37 |
+-------+
Facciamo il nostro secondo iadd
:
iadd # Pops those off the stack, adds them, and pushes the result
che ci dà:
+-------+
| stack |
+-------+
| 42 |
+-------+
(Che è, naturalmente, il Answer to the Ultimate Question of Life the Universe and Everything.)
Vedere http://blogs.msdn.com/b/ericlippert/archive/2011/11/28/why-have-a-stack.aspx - qui discuto lo stack di operandi CLR, ma i principi qui si applicano ugualmente bene alla JVM. –