Delphi 最佳化的 BUG? |
尚未結案
|
reptile2015
一般會員 發表:2 回覆:6 積分:1 註冊:2007-02-03 發送簡訊給我 |
[code delphi] procedure TfrmMain.Button1Click(Sender: TObject); var sum, index: integer; NumberList: array[0..4] of integer; begin NumberList[0] := 0; NumberList[1] := 0; NumberList[2] := 1; NumberList[3] := 1; NumberList[4] := 1; sum := 0; for index := 0 to 3 do begin // sum := sum index; if NumberList[index] = 0 then ShowMessage('0') else ShowMessage('1'); end; end; [/code] 日前幫同事 DEBUG 他的程式邏輯就類似上述那個樣子 因為結果不太對,所以就在 for index := 0 to 3 do 那行設中斷點 結果,一 Trace 之下,不得了,index 居然是從 4 開始跑 明明後頭就有 if NumberList[index] = 0 要用到 index 如果 index 從 4 開始跑,那結果怎麼會對? 一開始就猜到是 Delphi 最佳化的問題 所以在 Compiler 中,把 Code Optimization 關掉,果然 index 就乖乖從 0 開始跑 猜測 Delphi 是認為 for-loop 裡沒用到 index 所以才隨便讓 index 從 4 跑 (可是 NumberList[index] 不就有用到 index 嗎?) 我在開啟 Code Optimization 情況下,在 for-loop 硬加上那行 sum := sum index; 果然可以成功讓 index 從 0 開始跑 事後,同事是發現有一個地方寫錯 修改了一下,就得到正確的結果,就沒有去深思 這段 Code,明明要判斷 NumberList[index] 為什麼 Delphi 還會讓 index 從 4 開始跑 我是一直在思索,Delphi 的最佳化,不太可能會錯 可是我無法解釋為什麼 index 會從 4 開始走,而我的程式碼 明明要讓 index 從 0 開始走,去判斷 NumberList[index] 那,這樣這段程式碼的結果,怎麼會對? 各位可以實驗看看 -- 事後我是發現,不管 Delphi 讓 index 從 0 開始,還是從 4 開始 都會得到正確的結果,所以 Delphi 的最佳化還是正確的,沒有問題 只是,為什麼 if NumberList[index] 會得到正確的結果呢?(明明 index 的值,因為最佳化變了啊?) 我是有想到一個解釋啦,不過,先賣個關子,讓大家腦力激盪一下 編輯記錄
|
shinhrn
中階會員 發表:54 回覆:165 積分:83 註冊:2002-06-05 發送簡訊給我 |
|
cobraliu
中階會員 發表:15 回覆:75 積分:83 註冊:2007-11-22 發送簡訊給我 |
|
SmallBare
一般會員 發表:2 回覆:11 積分:2 註冊:2003-10-20 發送簡訊給我 |
|
mackevin
一般會員 發表:0 回覆:11 積分:2 註冊:2003-06-22 發送簡訊給我 |
|
wuabc
初階會員 發表:6 回覆:60 積分:33 註冊:2002-10-28 發送簡訊給我 |
http://www.drbob42.com/delphi/perform.htm
Loop Induction Variables The compiler automatically uses loop induction variables as a way to speed up access to arrays or strings within loops. If a variable is used only as an index into an array, for example in a for loop, the compiler will "induce" the variable, eliminating multiplication operations and replacing them with a pointer that is incremented to access items in the array. In addition, if the variable size is a 1, 4 or 8, Intel scale indexing is used to provide additional performance benefits. |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |