beginner's question about passing arrays as arguments to methods

G

gigaday

I am doing a little script that builds an array (called darray) of all
filenames in a directory tree. I am doing this by recursively calling
a method (called enter_dir) and passing the partially filled array
(called darray) down through the recursive calls.

The code works, but I am concerned about the efficiency of passing what
is potentially quite a large array around so many times. Should I be
concerned about this or not?

I also wrote the code using a global array ($darray) and this worked
too and didn't need to array to be passed down through the recursions.

What are the pros and cons of these two approaches?


def enter_dir(this_dir, darray)
farray = []
this_dir.each {|fname|
farray << fname
}
farray.each {|fname|
file_path = this_dir.path + '/' + fname
if File.stat(file_path).directory?
this_dir_sub = Dir.new(file_path)
if fname != '.' && fname != '..'
enter_dir(this_dir_sub, darray)
end
else
darray << file_path
end
}
end

this_dir = Dir.new('/home/tony/Ruby/dot_recycle')
darray = []
enter_dir(this_dir, darray)
puts darray
 
F

Farrel Lifson

I am doing a little script that builds an array (called darray) of all
filenames in a directory tree. I am doing this by recursively calling
a method (called enter_dir) and passing the partially filled array
(called darray) down through the recursive calls.

The code works, but I am concerned about the efficiency of passing what
is potentially quite a large array around so many times. Should I be
concerned about this or not?

I also wrote the code using a global array ($darray) and this worked
too and didn't need to array to be passed down through the recursions.

What are the pros and cons of these two approaches?


def enter_dir(this_dir, darray)
farray = []
this_dir.each {|fname|
farray << fname
}
farray.each {|fname|
file_path = this_dir.path + '/' + fname
if File.stat(file_path).directory?
this_dir_sub = Dir.new(file_path)
if fname != '.' && fname != '..'
enter_dir(this_dir_sub, darray)
end
else
darray << file_path
end
}
end

this_dir = Dir.new('/home/tony/Ruby/dot_recycle')
darray = []
enter_dir(this_dir, darray)
puts darray

You're not actually passing the array around whenever you call
enter_dir, rather you're passing a reference to the object, so the
performance penalties should not be noticable at all.

Farrel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top