2

This code to check mp3 songs (using recursion)is making my explorer very slow please suggest me a way to make it faster

public static boolean getMp3s1(File dir){
            int h=0;
             File[] listFile = dir.listFiles();
             if(listFile!=null)
             for( int i=0; i< listFile.length; i++)
             {
                 if(listFile[i].isDirectory()==true)
                 getMp3s1(listFile[i]);
                 else
                 {
                     if(listFile[i].getName().endsWith(".mp3")==true||listFile[i].getName().endsWith(".MP3")==true)
                         h=1;
            }

          }
         if(h==1){
             h=0;
             return true;
        }
         else
             return false;

        }
Animesh Mangla
  • 773
  • 7
  • 31
  • http://stackoverflow.com/questions/9530921/list-all-the-files-from-all-the-folder-in-a-single-list. Hope this will help you. – PraveenKumar.erakkingal Aug 05 '15 at 11:05
  • Whenever a method is called it puts all the code ahead of the call into a stack bring code inside the function to execution and after completion bring original code out of stack and into execution. This happens over and over again in recursion and multiple stacks are created the higher the number of calls the slower the program becomes Thus you could do the same in a infinite for loop which exits only on a break and still be more efficient – Domain Aug 05 '15 at 11:05
  • 1
    @PraveenKumar Bro i asked to resolve recursion .the code u mentioned is to get all fies and folders.........my code is to check whether a folder and its subfolders contains mp3 file or not .thats why i need to use recursion and that made my application slow.........still thanks a lot to reply – Animesh Mangla Aug 05 '15 at 11:08
  • @WisdmLabs can u give any example of implementing this by for loop .as i cannt do this by for loop... – Animesh Mangla Aug 05 '15 at 11:09
  • You could try something like this but its in java so you would have to make some changes http://stackoverflow.com/questions/3154488/best-way-to-iterate-through-a-directory-in-java – Domain Aug 05 '15 at 11:53

1 Answers1

1

try to break your loop after h=1; it can speed up a little. like this bellow:

public static boolean getMp3s1(File dir){
        int h=0;
         File[] listFile = dir.listFiles();
         if(listFile!=null)
         for( int i=0; i< listFile.length; i++)
         {
             if(listFile[i].isDirectory()==true)
             getMp3s1(listFile[i]);
             else
             {
                 if(listFile[i].getName().endsWith(".mp3")==true||listFile[i].getName().endsWith(".MP3")==true)
                    {
                      h=1;
                     break;
                    }
        }

      }
     if(h==1){
         h=0;
         return true;
    }
     else
         return false;

    }

EDIT: as i see from your code logic it seems that you can skip getMp3s1(listFile[i]); too.