我有两个示例函数 TestComplexityIf
和 TestComplexitySwitch
. VisualStudio-2017 的“计算代码度量”工具报告了 switch
函数的圈复杂度为 10声明广告 7 的声明 if-else
.我想知道 TestComplexitySwitch() 的复杂度是如何计算的。
private static void TestComplexityIf(String arg)
{
if (arg == "a")
{ }
else if (arg == "b")
{ }
else if (arg == "c")
{ }
else if (arg == "d")
{ }
else if (arg == "d")
{ }
else if (arg == "f")
{ }
else if (arg == "g")
{ }
}
private static void TestComplexitySwitch(String arg)
{
switch (arg)
{
case "a":
break;
case "b":
break;
case "c":
break;
case "d":
break;
case "e":
break;
case "f":
break;
case "g":
break;
}
}
另外,如果我评论最后一种情况,复杂性会突然变为 6。
private static void TestComplexitySwitch(String arg)
{
switch (arg)
{
case "a":
break;
case "b":
break;
case "c":
break;
case "d":
break;
case "e":
break;
case "f":
break;
//case "g":
//break;
}
}
最佳答案
Visual Studio Cyclomatic Complexity (CC) 工具根据 IL 代码计算值,因此受编译器详细信息的约束。
在这里,您偶然发现了一个性能编译器细节:当一个字符串的切换严格超过 6 种情况时,编译器会创建一个哈希表以进行快速字符串搜索。这个哈希表没有出现在 C# 代码中,而只出现在 IL 代码中。 IL 代码处理这个哈希表变得更加复杂,你会得到意想不到的 CC 值。 this link from Michael Randall很好地说明了这种情况。 .
或者,您可以使用工具 NDepend 到 compute the CC from C# source code , visualize CC values in a colored treemap并运行 some rules to forbid too complex methods .
(免责声明我为 NDepend 工作)
关于c# - 为什么 `switch` 代码的圈复杂度比 'if-else' 高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60735108/