c# - 哪个胜过另一个?(与字符串相关)

标签 c# string performance text indexof

<分区>

我不知道 String 对象的 IndexOf() 方法是如何工作的,所以我想知道在以下 2 个实现中哪个优于另一个:

首先,我想稍微介绍一下这个问题,简单地说,这里实现的函数/方法只有一个字符作为参数,它应该给出/返回与传入的字符对应的另一个字符。(规则下面给出了源字符集合和目标字符集合之间的匹配:

a <=> 9
b <=> 8
c <=> 7
d <=> 6
e <=> 5
f <=> 4
g <=> 3
h <=> 2
i <=> 1
j <=> 0

请注意,以上规则只是为了便于遵循,它不是固定规则,它可以是任何规则,因此不要基于该规则以其他方式实现这些方法。

现在是我想比较的 2 种方法:

1。第一个很短,基于 IndexOf()

string source = "abcdefghij";
string destination = "9876543210";
public char SourceToDest(char c){
    return destination[source.IndexOf(c)];//Suppose the c is always in source.
}

2。第二个更长,使用 switch case:

public char SourceToDest(char c){
  switch(c){
     case 'a': return '9';
     case 'b': return '8';
     case 'c': return '7';
     case 'd': return '6';
     case 'e': return '5';
     case 'f': return '4';
     case 'g': return '3';
     case 'h': return '2';
     case 'i': return '1';
     case 'j': return '0';
  }
}

正如我之前提到的,这个规则是为了容易遵循,如果没有注意到这一点,你可能有另一种方法是这样的:

public char SourceToDest(char c){
    return (char)(154 - (int)c); //154 = 106 + 48
} 

如果您有另一种方法优于我介绍的两种方法,请与我分享。

最佳答案

您可以使另一种方法更容易遵循,而且速度仍然很快:

public char SourceToDest(char c)
{
    return (char)((int)'j' - (int)c + (int)'0');
}

另一种选择是:

const string destination = "9876543210";
public char SourceToDest(char c)
{
    return destination[(int)c - (int)'a'];
}

这将比您的其他两种方法更快。

关于c# - 哪个胜过另一个?(与字符串相关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16122914/

相关文章:

c# - WPF Mahapps - 如何隐藏汉堡菜单集合中的选项卡?

python - 如何查找重复字母并将其从列表中的字符串中全部删除

mysql - 在存储过程中将 string 转换为 int

java - 多次迭代列表的性能成本是多少

c# - .NET 中最快的 GZIP 解压库

java - 进一步优化我的充满 for 循环的 Java 代码

c# - BackgroundDownloader 不适用于 Windows 10 移动版 UWP?

c# - 为 dataGridView 中的特定列设置默认列值

c# - IndexOutOfRangeExpection 发生在 Dictionary.Add 方法上

java - java.io FileOutPutStream-字符之间有空格。为什么?