博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
拒绝switch,程序加速之函数指针数组
阅读量:4647 次
发布时间:2019-06-09

本文共 1663 字,大约阅读时间需要 5 分钟。

先看一个使用switch语句的程序:

#include 
#include
//加法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 
#include
//加法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语句产生类似的效果。

转载于:https://www.cnblogs.com/lytwajue/p/7093325.html

你可能感兴趣的文章
IT男专用表白程序
查看>>
读《大道至简》第六章感想
查看>>
ef linq 中判断实体中是否包含某集合
查看>>
章三 链表
查看>>
Solution for Concurrent number of AOS' for this application exceeds the licensed number
查看>>
CSE 3100 Systems Programming
查看>>
IntelliJ IDEA 的Project structure说明
查看>>
Java Security(JCE基本概念)
查看>>
Linux Supervisor的安装与使用入门
查看>>
创建 PSO
查看>>
JasperReport报表设计4
查看>>
项目活动定义 概述
查看>>
团队冲刺04
查看>>
我的Python分析成长之路8
查看>>
泛型在三层中的应用
查看>>
SharePoint2010 -- 管理配置文件同步
查看>>
.Net MVC3中取得当前区域的名字(Area name)
查看>>
获得屏幕像素以及像素密度
查看>>
int与string转换
查看>>
adb命令 判断锁屏
查看>>