高效的switch语句 [英] Efficient switch statement

查看:44
本文介绍了高效的switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面两个版本的switch case中,我想知道哪个版本的效率更高.

In the following two versions of switch case, I am wondering which version is efficient.

1:

string* convertToString(int i)
{
    switch(i)
    {
    case 1:
        return new string("one");
    case 2:
        return new string("two");
    case 3:
        return new string("three");
        .
        .
    default:
        return new string("error");
    }
}

2:

string* convertToString(int i)
{
    string *intAsString;
    switch(i)
    {
    case 1:
        intAsString = new string("one");
        break;
    case 2:
        intAsString = new string("two");
        break;
    case 3:
        intAsString = new string("three");
        break;
        .
        .
    default:
        intAsString = new string("error");
        break;
    }
return intAsString;
}

1:有多个return语句会导致编译器产生额外的代码吗?

1: has multiple return statements will it cause compiler to generate extra code?

推荐答案

这是一个过早的优化问题.

This is a premature optimization worry.

前一种形式更清晰,源代码行更少,这当然是选择它的一个令人信服的理由(在我看来).

The former form is clearer and has fewer source lines, that is a compelling reason to chose it (in my opinion), of course.

您应该(像往常一样)分析您的程序以确定此函数是否甚至在优化的热门列表"中.这将告诉您使用 break 是否会降低性能.

You should (as usual) profile your program to determine if this function is even on the "hot list" for optimization. This will tell you if there is a performance penalty for using break.

正如评论中所指出的,这段代码的主要性能罪魁祸首很可能是动态分配的字符串.一般在实现这种整数到字符串"的映射函数时,应该返回字符串常量.

As was pointed out in the comments, it's very possible that the main performance culprit of this code is the dynamically allocated strings. Generally, when implementing this kind of "integer to string" mapping function, you should return string constants.

这篇关于高效的switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆