首页 > 代码库 > 递归算法和栈运行效率的比较

递归算法和栈运行效率的比较

昨天写了一个递归程序遍历计算机上所有的文件,有网友说递归速度很慢,于是今早写了一个使用栈遍历计算机文件的程序,虽然计算机对递归算法的实现最终还是靠栈来实现。但和自己写的运行效率还有有些差别。

以下是时间对比,第一张图是使用得递归算法,第二张图使用的栈,使用栈来实现还是要快那么一点。使用递归的程序请参考我昨天的博客。

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            List<string> allFileName = new List<string>();
            string[] drives = Directory.GetLogicalDrives();
            Stack<string> stack = new Stack<string>();
            foreach (string drive in drives)
            {
                stack.Push(drive);
            }
            string path;
            DirectoryInfo sDir;
            FileInfo[] fileArray;
            DirectoryInfo[] subDirArray;
            while (stack.Count > 0)
            {
                path = stack.Pop();
                sDir = new DirectoryInfo(path);
                try
                {
                    fileArray = sDir.GetFiles();
                    foreach (FileInfo file in fileArray)
                    {
                        allFileName.Add(file.FullName);
                    }
                }
                catch (Exception e)
                {
                }

                try
                {
                    subDirArray = sDir.GetDirectories();
                    foreach (DirectoryInfo subDir in subDirArray)
                    {
                        stack.Push(subDir.FullName);
                    }
                }
                catch (Exception e)
                {
                }
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed);
            Console.WriteLine(allFileName.Count);      
            Console.ReadLine();
        }      
    }
}

递归算法和栈运行效率的比较