Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the run time of shift/unshift in a ruby array

Tags:

big-o

ruby

Does anyone know how efficient shift and unshift are in a ruby array?

Deleting from the beginning of an array and having to move every element in memory can become very inefficient. I assume ruby does this some other way.

Any info on the following would be helpful:
- Algorithmic runtime
- Implementation
- General efficiency
- Would shift/unshift be acceptable to use for a queue (in something like C++ this would not)

Thank you!

like image 518
djburdick Avatar asked Dec 02 '11 07:12

djburdick


People also ask

What does Unshift do in Ruby?

unshift() method in Ruby is used to fill the array with elements that will begin at the front of the array. It appends elements passed in as arguments to the front of the original array.

What is the difference between shift and Unshift?

What are Shift() and Unshift() methods in JavaScript. The shift() method is used to remove an element/item from the starting point of an array. The unshift() method is used to add an element/item to the starting point of an array.

How do you shift in Ruby?

The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element. Return Value: It returns the first element which is at the front of the SizedQueue and removes it from the SizedQueue.

What is the difference between the array Unshift () and the array shift () elements?

Definition: shift(): this method is use to remove first element of an array and returns new array. unshift(): this array method is used to add one or more arrays in existing array list and returns new array.


1 Answers

In older versions of Ruby (before ~2012), unshift was an O(n) operation. However, an optimization was added in this commit and released in Ruby 2.0.0 that makes the unshift amortized O(1), meaning that it is guaranteed, on average, to be O(1), but an individual operation may be O(n). This is the same running time as shift.

This CS Stack Exchange post has a good explanation of how this works and how you end up with an O(1) amortized running time (it's about C++'s vector::push_back, but it works the same way).

like image 140
Kerrick Staley Avatar answered Sep 21 '22 03:09

Kerrick Staley