Perhaps not related to the speed problem: Your code may open a lot of directory handles while recursing, blocking some resources. File and directory handles should generally be treated as a limited resource. Your code should close the directory handle BEFORE recursing into the filesystem, not after. You could read the entire directory contents into an array, close the handle, and then iterate over the array.

An even better way would be a queue (think of it as a to-do-list) instead of using recursion. The queue is a simple array that starts with the directory to be "explored". While the array is not empty, shift out the first element and use it as a directory name to open a directory handle. Read all directory elements, push subdirectories to the array, handle non-directories directly in the loop. Close the directory handle.

Perhaps related to the speed problem: If the output is initially fast and slows down over time, you are leaking resources, forcing the system to start swapping. Your code uses close instead of closedir to close $DIR. close can not close the directory handle. You would have noticed that if you had added proper error handling (... or die "Can't close: $!" or autodie):

>perl -Mstrict -w -e 'opendir my $dir,"." or die "opendir: $!";close $ +dir or die "close: $!";' close: Bad file descriptor at -e line 1.

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

In reply to Re: print all files is soo slow! Why? by afoken
in thread print all files is soo slow! Why? by harangzsolt33

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.