for+if語句 和 僅用if語句 的程序效率
以下為在VC++6.0環境下對程序效率(時間,空間)分析的過程和結論:1 程序代碼#include "stdafx.h"#include <stdio.h>int main(){int number[10] ={1212,1212,1,2,4,5,6,7,8,999999};int max;max=number[0];for(int i=1;i<10;i++){if(max<number[i]){max=number[i];}}if (max<number[1]){max=number[1];}if (max<number[2]){max=number[2];}if (max<number[3]){max=number[3];}if (max<number[4]){max=number[4];}if (max<number[5]){max=number[5];}if (max<number[6]){max=number[6];}if (max<number[7]){max=number[7];}if (max<number[8]){max=number[8];}if (max<number[9]){max=number[9];}return 0;}2 問題提出: 上面程序代碼查找10個數中的最大值,分別使用for +if語句,和9個單獨的if語句,請問上述兩種方法,哪一種程序效率較高?為什么?3 分析3.1 for+if語句的反匯編代碼13: for(int i=1;i<10;i++)00401074 mov dword ptr [ebp-30h],10040107B jmp main+76h (00401086)0040107D mov ecx,dword ptr [ebp-30h]00401080 add ecx,100401083 mov dword ptr [ebp-30h],ecx00401086 cmp dword ptr [ebp-30h],0Ah0040108A jge main+94h (004010a4)14: {15: if(max<number[i])0040108C mov edx,dword ptr [ebp-30h]0040108F mov eax,dword ptr [ebp-2Ch]00401092 cmp eax,dword ptr [ebp+edx*4-28h]00401096 jge main+92h (004010a2)16: {17: max=number[i];00401098 mov ecx,dword ptr [ebp-30h]0040109B mov edx,dword ptr [ebp+ecx*4-28h]0040109F mov dword ptr [ebp-2Ch],edx18: }19: }004010A2 jmp main+6Dh (0040107d)3.2 獨立的9個if語句的反匯編代碼(以第一個if語句為例)22: if (max<number[1])004010A4 mov eax,dword ptr [ebp-2Ch]004010A7 cmp eax,dword ptr [ebp-24h]004010AA jge main+0A2h (004010b2)23: {24: max=number[1];004010AC mov ecx,dword ptr [ebp-24h]004010AF mov dword ptr [ebp-2Ch],ecx25: }3.3 分析: 1)使用for + if ,每次循環需要執行13個匯編代碼,循環代碼最大可能執行:9 * 13 = 117條指令; 2)使用獨立if語句,每次執行5條判斷語句,9個if代碼判斷最大執行代碼量為9 * 5 = 45 條指令; 程序效率分析(運行時間和占用內存空間的分析)因此從程序時間效率上分析,2)的時間效率會比較高。
但從空間上分析,1)的效率會比較高,循環執行一共使用15條指令;2)的效率不高(45條指令空間)。 實際的編程使用建議 :一般實際使用1)方法的話,代碼會比較容易維護,2)在實際應用中顯得不是很專業的做法!。
java else if 為什么比 switch 效率低
(1)盡管switch語句與if語句一樣,是條件選中語句,但實際上switch語句只能取代if語句的一部分功能。
switch語句只能做等式比較,即用switch之后括號內的表達式結果與各case分支后的常量做相等比較,如相等則執行case后的語句,否則跳過;而if語句可做各種關系比較。(2)switch之后括號內的表達式只能是整型(byte、short、char和int)、枚舉型或字符型表達式,不能是長整型或其他任何類型。
switch就像是多彩的盒子,你一眼就可以分辯出來,但是if相當于在盒子中加了個外包裝,你得一個一個的看,才知道是哪個。GOOD LUCK。