C sprintf的这两种用途在性能上有区别吗?
我试图根据变量的值打印一周中的不同日期。每天都由一个特定的数字映射 我想把数字转换成星期一、星期二等。例如:C sprintf的这两种用途在性能上有区别吗?,c,performance,printf,C,Performance,Printf,我试图根据变量的值打印一周中的不同日期。每天都由一个特定的数字映射 我想把数字转换成星期一、星期二等。例如: #include <stdio.h> int main(){ int a=1; char buf[16]; sprintf(buf,"%s",a==1?"Monday":a==2?"Tuesday":a==3?"Wednesday":a==4?"Thursday":a==5?"Friday":a==6?"Saturday":a==7?"Sunday":
#include <stdio.h>
int main(){
int a=1;
char buf[16];
sprintf(buf,"%s",a==1?"Monday":a==2?"Tuesday":a==3?"Wednesday":a==4?"Thursday":a==5?"Friday":a==6?"Saturday":a==7?"Sunday":"Unknown day");
printf("%s",buf);
return 0;
}
那么,这两者在内存使用或性能方面是否存在差异?性能差异当然可以忽略不计。在幕后,我们正在考虑更多的取消引用 示例中的所有字符串都将存储在只读内存(字符串文字所在的位置)中,并且很可能存储在相邻的内存位置(彼此相邻)。既然如此,组成这些字符串的所有字符也很可能被机器存储在CPU缓存中,从而将访问时间减少到无法检测的程度 真正影响效率的是嵌套的三元运算符。这将生成比需要多得多的程序集 更好的方法是在映射到它们的特定索引处拥有一个值数组。例如:
char * days[] = {"Monday", "Tuesday", "Wednesday", ...};
sprintf(buf, "%s", days[a - 1]);
注意:
a-1
,因为在您的示例中,a
似乎从1开始。最好不要太花哨
/* Returns name of given day of the week,
* where Monday is day 1, and Sunday is day 7.
*/
const char *dayofweek(int day)
{
switch (day) {
case 1: return "Monday";
case 2: return "Tuesday";
case 3: return "Wednesday";
case 4: return "Thursday";
case 5: return "Friday";
case 6: return "Saturday";
case 7: return "Sunday";
default: return NULL;
}
}
int main(void)
{
int i;
for (i=0; i<10; ++i) {
const char *day = dayofweek(i);
printf("Day %d of the week is %s\n", i, day ? day : "[invalid]");
}
return 0;
}
/*返回一周中给定日期的名称,
*其中周一是第一天,周日是第七天。
*/
常量字符*dayofweek(整数天)
{
开关(日){
案例1:返回“星期一”;
案例2:返回“星期二”;
案例3:返回“星期三”;
案例4:返回“星期四”;
案例5:返回“星期五”;
案例6:返回“星期六”;
案例7:返回“星期日”;
默认值:返回NULL;
}
}
内部主(空)
{
int i;
对于(i=0;如果存在性能差异,则性能差异可能可以忽略不计。尤其是与读取代码的笨拙相比。数组查找将击败这两个版本。数组查找也将更容易翻译为其他语言。代码使用最清楚地表达意图的结构。仅在需要时和需要时进行优化,并且o探查器也是如此。这两种表单都是即将发生的维护难题,而第二种表单在这方面更糟糕。查找表将同样快速且更易于维护。
/* Returns name of given day of the week,
* where Monday is day 1, and Sunday is day 7.
*/
const char *dayofweek(int day)
{
switch (day) {
case 1: return "Monday";
case 2: return "Tuesday";
case 3: return "Wednesday";
case 4: return "Thursday";
case 5: return "Friday";
case 6: return "Saturday";
case 7: return "Sunday";
default: return NULL;
}
}
int main(void)
{
int i;
for (i=0; i<10; ++i) {
const char *day = dayofweek(i);
printf("Day %d of the week is %s\n", i, day ? day : "[invalid]");
}
return 0;
}