拒絕switch,程式加速之函數指標數組,switch數組

來源:互聯網
上載者:User

拒絕switch,程式加速之函數指標數組,switch數組
先看一個使用switch語句的程式:

#include <stdio.h>#include <time.h>//加法int add(int a,int b){return a+b;}//減法int subtract(int a,int b){return a-b;}//乘法int multi(int a,int b){return a*b;}//除法int divide(int a,int b){return a/b;}int claculate(int a,int b,char oper){//這裡使用switch語句switch (oper){case '+':return add(a,b);case '-':return subtract(a,b);case '*':return multi(a,b);case '/':return divide(a,b);default:return -1;break;}}void main(){int a = 250;int b = 5;//統計程式已耗用時間clock_t start, finish; start = clock();printf("%d\n",claculate(a,b,'+'));printf("%d\n",claculate(a,b,'-'));printf("%d\n",claculate(a,b,'*'));printf("%d\n",claculate(a,b,'/'));finish = clock();printf( "%f seconds\n", (double)(finish - start) / CLOCKS_PER_SEC );  }
再看一個使用函數指標數組的程式
#include <stdio.h>#include <time.h>//加法int add(int a,int b){return a+b;}//減法int subtract(int a,int b){return a-b;}//乘法int multi(int a,int b){return a*b;}//除法int divide(int a,int b){return a/b;}int claculate(int a,int b,int oper){//其實這裡應該使用hashMap,將字元'+'映射到add函數。//直接使用數字是為了簡便//聲明指向函數指標的數組int (*pfunc[])(int a,int b)  = {add,subtract,multi,divide};return pfunc[oper](a,b);}void main(){int a = 250;int b = 5;//統計程式已耗用時間clock_t start, finish; start = clock();printf("%d\n",claculate(a,b,0));printf("%d\n",claculate(a,b,1));printf("%d\n",claculate(a,b,2));printf("%d\n",claculate(a,b,3));finish = clock();printf( "%f seconds\n", (double)(finish - start) / CLOCKS_PER_SEC );  }

當switch判斷語句中case的個數不多時,上面兩個程式差不多。但如果case很多時,使用函數指標數組要快很多。類似地,在Java裡面也可以使用反射來取代swith語句產生類似的效果。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.