拒绝switch,程序加速之函数指针数组

15 篇文章 1 订阅

先看一个使用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语句产生类似的效果。


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值