C#避免回溯方法心得
本文實例講述了C#避免回溯方法,分享給大家供大家參考之用。具體分析如下:
首先,回溯法是不可控的,有時候會超出我們意料之外產(chǎn)生不妙的結果,最常見的也就是內存泄漏。。
回溯方法是很容易想到,又不容易想到的,往往,我們思維更容易進入的是回溯法。但是回溯法有著它的弊端,非常明顯的弊端是作用域內產(chǎn)生的變量和引用在回溯法調用未完成時,不能釋放(對于大部分編輯器來說,排除有著優(yōu)化能力的編輯器)。如果我們在某一方法中使用極多的回溯調用,在方法中不能及時的對方法作用域內的變量和引用釋放,最終會造成內存不足和cpu的計算負荷增大(內存機制中可以將過剩的數(shù)據(jù)轉存到虛擬內存、硬盤,這個就不說了)。使用棧(隊)式的循環(huán),可以輕易避免回溯法,而且棧(隊)式的數(shù)據(jù)再使用之后可以很方便的拋出移除。某些時候就是這樣,一個小小的改動,可以讓一個程序在某種特定的環(huán)境中起死回生。(之前做過一個數(shù)獨運算器的算法,后來的優(yōu)化改進就是為了避免回溯)
示例代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace 避免回溯方法 { class Program { static void Main(string[] args) { string path = AppDomain.CurrentDomain.BaseDirectory; List<string> fileList1 = new List<string>(); FunctionHuishuo(path, ref fileList1); List<string> fileList2 = new List<string>(); FunctionQueue(path, ref fileList2); List<string> fileList3 = new List<string>(); FunctionStack(path, ref fileList3); } /// <summary> /// 回溯法 /// </summary> /// <param name="path"></param> /// <param name="fileList"></param> private static void FunctionHuishuo(string path, ref List<string> fileList) { if (true) { string[] files = null; try { files = Directory.GetFiles(path); } catch { } if (files != null && files.Length > 0) { fileList.AddRange(files); } } if (true) { string[] folders = null; try { folders = Directory.GetDirectories(path); } catch { } if (folders != null && folders.Length > 0) { foreach (string folder in folders) { FunctionHuishuo(folder, ref fileList); } } } } /// <summary> /// 堆棧法 /// </summary> /// <param name="path"></param> private static void FunctionStack(string path, ref List<string> fileList) { Stack<string> stack = new Stack<string>(); stack.Push(path); while (stack.Count > 0) { string dir = stack.Pop(); string[] files = null; try { files = Directory.GetFiles(dir); } catch { } if (files != null && files.Length > 0) { fileList.AddRange(files); } string[] folders = null; try { folders = Directory.GetDirectories(dir); } catch { } if (folders != null && folders.Length > 0) { foreach (string folder in folders) { stack.Push(folder); } } } } /// <summary> /// 隊列法 /// </summary> /// <param name="path"></param> private static void FunctionQueue(string path, ref List<string> fileList) { Queue<string> queue = new Queue<string>(); queue.Enqueue(path); while (queue.Count > 0) { string dir = queue.Dequeue(); string[] files = null; try { files = Directory.GetFiles(dir); } catch { } if (files != null && files.Length > 0) { fileList.AddRange(files); } string[] folders = null; try { folders = Directory.GetDirectories(dir); } catch { } if (folders != null && folders.Length > 0) { foreach (string folder in folders) { queue.Enqueue(folder); } } } } } }
請仔細對比下三種循環(huán)結構的寫法,特別注意下里面有用到 if(true){...} ,這種方式在某些編輯環(huán)境中可以產(chǎn)生非常美妙的效果。
相信本文所述對大家C#程序設計的學習有一定的借鑒價值。
相關文章
c# 使用特定帳號密碼訪問Windows網(wǎng)路共享
這篇文章主要介紹了c# 使用特定帳號密碼訪問Windows網(wǎng)路共享的方法,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下2021-03-03