开发者

Optimize string comparison in C#

I have the following code on an asp.net button click

if(str == ipaddr1 || ipaddr2 || ipaddr3 || ipaddr4 || ipaddr5 || ipaddr6 || ipaddr7)
// do this
else
//cancel click event

How can I optimize this piece of code?

Update: Apologies everyone! I did not mean to compare it with the literal string ipadd开发者_运维问答r. I mean to compare it to the value ipaddr1, ipaddr2 holds and so on


replace with:

Regex.IsMatch(str, "^ipaddr[1-7]$")

Optimised for readability not necessarily performance.


HashSet<T> is the best container to check containing:

var ips = new HashSet<string> { "ip1", "ip2", "ip3", "ip4", "ip5" };
if (ips.Contains(input))
{
    // do stuff
}

For any type:

var ips = new HashSet<IPHostEntry> { ip1, ip2, ip3, ip4, ip5 };
if (ips.Contains(input))
{
    // do stuff
}

Was:

if(str = qry.StartsWith("23.55") || str = qry.StartsWith("xuz") || str = qry.StartsWith("i3") || str = qry.StartsWith("i444") || str = qry.StartsWith("ki5") || str = qry.StartsWith("65fr6")) // do this else // do this

Become:

var arr = new[] { "23.55", "xuz", "i3",  "i444", "ki5", "65fr6") };
if (arr.Any(str => input.StartsWith(str, StringComparison.Ordinal))
{
    // do stuff
}

StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase are very important for performance.


What about

if(str.Substring(0,6) == "ipaddr" && str[6] >= '1' && str[6] <= '7')

For your information, your original code does not even compile. This

if(str == "ipaddr1" || "ipaddr2" || "ipaddr3" || "ipaddr4" || "ipaddr5" || "ipaddr6" || "ipaddr7")

Needs to be replaced with this to compile

if(str == "ipaddr1" || str == "ipaddr2" || str == "ipaddr3" || str == "ipaddr4" || str == "ipaddr5" || str == "ipaddr6" || str == "ipaddr7")

So the original code is actually even more tedious than you thought.

UPDATE

According to your updated question, the best option is to put your string variables into a List<string> called, for example ipaddr. Then to see if the string str is included, simply do this:

if( ipaddr.Contains( str ) )
{
   //contained in the list
}


I would do something like:

str.Length == 7 && str.StartsWith("ipaddr") && str[6] > '0' && str[6] < '8'

Edit:

After your update, I would do something like:

string[] validStrings = { ipaddr1, ipaddr2, ... };
bool isStrValid = validStrings.Contains(str);

For better performance, consider using a HashSet<string> instead of an array, especially if the list of valid strings doesn't change.


Both more readable, and more performant would be:

switch(str)
{
case "ipaddr1": 
case "ipaddr2":
case "ipaddr3":
case "ipaddr4":
case "ipaddr5":
case "ipaddr6":
case "ipaddr7":
    //do something
    break;
default:
    //do something else
    break;
}

(although, admittedly massively verbose...)


I would do a

List<string> variables = new List<string> { "ip1","ip2","ip3","ip4","ip5" };

if (variables.Contains(inputstring))
  ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜