For example, given n
, which may be 1000000
or 100000000
, to find out
0 ^ 1 ^ 2 ^ 3 ^ ... ^ n
there can be several ways:
p (0..n).inject(:^)
p 0.upto(n).inject(:^)
p (n+1).times.inject(:^)
(is there any other common ways to do this in Ruby?) Which of the common ways to loop through a range in Ruby actually creates an array and therefore may cause huge memory usage? (as a general rule to remember).
On a Mac, are there ways either inside of the Ruby program and by using the OS to tell that the memory use is in fact minimal (O(1) space) to verify that no actual array is created?
P.S. one way is to make n
quite big such as 100000000
, run it, and use ps v
in another shell to see that memory is at a low % (as compared to running a program with (0..n).to_a.inject(:^)
), but I am not sure if there is a better way.