Use a hash, not an array, hashes are better for bigger amounts of objects,
That is not true. Whether to use Hash or Array is determined not by
the amount of objects to be put inside but by the key type and usage
patterns. Hashes are only better if you need non integer indexes or
have holes in the sequence of integer keys. Because the way Hash works
it will likely take more memory for one million entries indexed by 0
... 1_000_000 than the corresponding Array instance.
irb(main):005:0> Benchmark.bmbm do |x|
irb(main):006:1* x.report("array 1") { Array.new(1_000_000) }
irb(main):007:1> x.report("array 2") { a=; for i in 0 ... 1_000_000;
a[i]=a; end }
irb(main):008:1> x.report("hash") { h={}; for i in 0 ... 1_000_000;
h[i]=h; end }
irb(main):009:1> end
Rehearsal -------------------------------------------
array 1 0.000000 0.000000 0.000000 ( 0.004964)
array 2 0.078000 0.000000 0.078000 ( 0.086736)
hash 0.609000 0.015000 0.624000 ( 0.623278)
---------------------------------- total: 0.702000sec
user system total real
array 1 0.000000 0.000000 0.000000 ( 0.000741)
array 2 0.062000 0.000000 0.062000 ( 0.066444)
hash 0.421000 0.000000 0.421000 ( 0.419497)
=> [#<Benchmark::Tms:0x0000060004f0f0 @label="array 1",
@real=0.0007412240083795041, @cstime=0.0, @cutime=0.0, @stime=0.0,
@utime=0.0, @total=0.0>, #<Benchmark::Tms:0x0000060004feb0
@label="array 2", @real=0.06644390399742406, @cstime=0.0, @cutime=0.0,
@stime=0.0, @utime=0.06200000000000028, @total=0.06200000000000028>,
#<Benchmark::Tms:0x0000060047cda8 @label="hash",
@real=0.41949673400085885, @cstime=0.0, @cutime=0.0, @stime=0.0,
@utime=0.4209999999999998, @total=0.4209999999999998>]
you could also use a YAML or JSON file if you really wanted to get fancy:
Those are used for external storage, not for manipulating objects in memory.
Any of these are a better option then an array for the amount you want to store
I beg to differ. Even Marshaling an Array with 1_000_000 elements is
not that big deal IMHO.
Cheers
robert
···
On Tue, Dec 8, 2015 at 3:24 AM, thomas Perkins <thomas.perkins23@icloud.com> wrote:
--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can
- without end}
http://blog.rubybestpractices.com/