哪个更有效?开关与循环 [英] Which is more effective? Switch vs. Loop
问题描述
大家好,
只是一个简单的问题....总的来说(如果使用C#,则在C#中),此开关比循环或另一种回合"更有效.谢谢!
Hi all,
Just a quick question.... in general (and in C# if that''s relevant) is a switch more effective than a loop or the other way ''round? Thanks!
推荐答案
它们是2种不同的东西..
您可以(应该)使用switch来避免多个if-else语句
只有一个代码执行
像for或foreach这样的循环将代码重复n次
they are 2 different things..
you can(should) use switch in order to avoid multple if-else statements
there is only one single code execution
loops like for or foreach repeteat the code n times
好了,读完您的注释后,您应该使用一种不允许重复的内容.
您实际上想做的是
Okay having read your comment, you should use a formulation that allows you not to repeat things.
What you''re actually trying to do is
return mapper.ResultByRowcountForGroupSearch(searchFacilitator_.SetId,
x,
dac);
...其中x是根据组类型设置的.
因此,我建议您设置一个Dictionary< int,string> (我认为您的组类型是int吗?),然后以静态方式或在封闭类的构造函数中填充它(如果映射是您可以在编译时编写的,则可能是静态填充),例如:
... where x is set based on the group type.
So I recommend you set up a Dictionary<int, string> (your group types are int I think?), and populate it either statically or in the constructor of the enclosing class (probably statically if the mappings are something you can write in at compile time), e.g.:
static Dictionary<int, string> groupTypeMap = new Dictionary<int, string>();
static ClassName(){ // static constructor
groupTypeMap[BRGroupTypeIds.Audit] = GroupSearchBatchStrings.AUDIT_TEMPSPACE_NAME;
// etc
}
然后,在您要询问的方法中,您可以做
Then in the method that you''re asking about, you can do
return mapper.ResultByRowcountForGroupSearch(searchFacilitator_.SetId,
groupTypeMap[searchFacilitator_.GroupType,
dac);
...,或者,如果可能不在一个组中,并且您不希望从查找中获取异常(即,您的switch语句的实际等效项):
... or, if it''s possible to not be in a group and you don''t want an exception from the lookup (i.e. the actual equivalent of your switch statement):
string typeName;
return groupTypeMap.TryGetValue(searchFacilitator_.GroupType, out typeName) ?
mapper.ResultByRowcountForGroupSearch(searchFacilitator_.SetId, typename, dac) :
0;
这篇关于哪个更有效?开关与循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!