I know that shift, push, and pop are Array methods used to add/remove elements of an array, but I am unsure of what is actually occuring in memory. Say for example the method pop which removes the last element of an array. It reminds me of the LIFO order used in the stack, but I assume the element isn’t really “popped” like in assembly programming; rather that the index of the entire array is shifted. I really don’t know so if anyone could help me out I would really appreciate it.
Share
Ruby is for programmers who suffers from the idea that you have. We trust those programmers who do the implementation that they can do best in optimizing performance and memory management.
If you are just curious, here is the code for Array#shift in Rubinius:
And you can see, an array itself is a Rubinius::Tuple, and in Tuple definition, it is an Rubinius::Array. What it does is just put the beginning position to the next one. I am not sure they will release the space it used (which I assume it will) because you have to dig deeper.
In official 1.9.3, I do not know how it is implemented as they do it in C, and they are hard to read. If you want to know more details, you can fork Rubinius on GitHub, or fork the official 1.9.3 from ruby-lang.org, and read the source code. You can learn more about C/C++ programming too 🙂
So I quickly went through the code of official 1.9.3, and this is the array#shift function definition:
This line:
It tells us it actually move the memory block offset by n. That is probably why the official runs slower than Rubinius… Rubinius takes advantage in large memory, but save time; official consumes less memory but takes more time…