Big O remark for Ruby methods?
3 answers
There is no list of the theoretical complexities of Ruby methods. You are interested in minitest/benchmark
which is used like this:
require 'minitest/autorun'
require 'minitest/benchmark'
class TestFoobar < Minitest::Benchmark
def setup
@foo_arrays = ( 1 .. 10_000 ).map { |n| [ 42 ] * n }
# Because default benchmarking range is [1, 10, 100, 1_000, 10_000]
end
def bench_foo_size
assert_performance_constant 0.99 do |n| @foo_arrays[ n ].size end
end
end
If you do the above test, you can see that the performance of the method is Array#size
constant. If you change #bench_foo_size
to:
def bench_foo_size
assert_performance_linear 0.99 do |n| @foo_arrays[ n ].size end
end
The test will indeed fail because it is Array#size
not linear but sublinear. minitest/benchmark
is flexible and you can apply it to your own code as well as embedded resources.
+4
source to share