In my string array, I want to look up some text and return the the line number of the first occurrence as an int.
This is working;
public static int LookUpLineNumber(String[] item, string TextToLookUp)
{
int m;
for (m = 0; m < item.Count(); m++)
{
if (item[m].Contains(TextToLookUp))
{
break;
}
}
return m++;
}
However, I am wondering if there is any way to optimize it for efficiency and length?
Speed comparison: (average time on 10.000 runs with an string array of size 10.000)
Using my code:
Using Habib's code: Array.FindIndex<string>(item, r => r.Contains(TextToLookUp));
Your current solution looks OK. You can have return m;
instead of return m++
.
If you want to shorten your code you can use Array.FindIndex<T>
like:
public static int LookUpLineNumber(String[] item, string TextToLookUp)
{
return Array.FindIndex<string>(item, r => r.Contains(TextToLookUp));
}
Not really sure if it would give you any performance gain.
If you need to do this multiple times, a suffix tree built out of the array would be the fastest approach:
http://en.wikipedia.org/wiki/Suffix_tree
However, if you are not re-using the array, then I think the approach you have is likely fastest, short of using a regex to do the contains, which may be faster if the regex is pre-compiled.
You can also do the following :-
Array.FindIndex(item,i=>i.Contains(TextToLookUp));
The above would work even if it is not sorted.
The above can be further optimized by using IndexOf
operations instead of Contains
and passing StringComparison.OrdinalIgnoreCase
. Then you will have to compare it against 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.