I found that the easiest and most accurate way to answer this question is to compare it.
require 'benchmark' Benchmark.bm do |x| iterations = 10000000 x.report("push") { a = [] iterations.times do a.push(10) end } x.report("unshift") { a = [] iterations.times do a.unshift(10) end } a = [] iterations.times do a.push(10) end x.report("shift") { iterations.times do a.shift() end } a = [] iterations.times do a.push(10) end x.report("pop") { iterations.times do a.pop() end } end
On my system running ruby version 2.0.0 this returns the results:
user system total real push 0.880000 0.030000 0.910000 ( 0.917213) unshift 0.920000 0.090000 1.010000 ( 1.026208) shift 0.780000 0.030000 0.810000 ( 0.810293) pop 0.710000 0.000000 0.710000 ( 0.724865)
It seems that push , pop , shift and unshift take about the same amount of time.
Re-running this code with different values for iterations gives me results that scale in proportion to the number of iterations changed. This means that regardless of the value of iterations each operation always takes on average the same time, that is, the execution time of each operation does not depend on the length of the array and therefore has an O(1) execution time.
I would say that it would be acceptable to use as a queue.
Simon baumgardt-wellander
source share