开发者

Is it efficient to use LINQ to parse strings?

I've been using LINQ so much in the last couple of weeks that when I had to write a one line function to remove < and > from a string,开发者_运维百科 I found that I had written it as a LINQ query:

Public Function StripLTGT(text As String) As String
    Return String.Join("", (From i As Char In text.ToCharArray Where i <> "<"c Where i <> ">"c).ToArray)
End Function

My question is, is it better to do it with LINQ as above or with StringBuilder as I've always done, as below:

Public Function StripLTGT(text As String) As String
    Dim a As New StringBuilder(text)
    a = a.Replace("<", "")
    a = a.Replace(">", "")
    Return a.ToString
End Function

Both work, the second one is easier to read, but the first one is designed for executing queries against arrays and other enumerables.


Regex.Replace("[<>]", "")

Is much more straightforward.

Or:

myString = myString.Replace("<", "").Replace(">", "")

Whether or not option A, B or C is faster than the others is hard to say because option A may be better on small strings while option B may be better on long strings, etc.


Either one should really be fine in terms of functionality. The first one is not efficient as is. The ToArray call is doing far more work than necessary (if you're on .NET 4.0, it is not needed anyway), and the ToCharArray call is not needed. Basically the characters in the input string are being iterated a lot more than they need to be, and extra arrays are allocated superfluously.

I wouldn't say this particularly matters; but you asked about efficiency, so that's why I mention it.

The second one seems fine to me. Note that if you wanted to go the one-line route, you could still do so with a StringBuilder and I think still have something more concise than the LINQ version (though I haven't counted characters). Whether or not this even outperforms the more direct String.Replace option is kind of unclear to me, though:

' StringBuilder.Replace version:
Return New StringBuilder(text).Replace("<", "").Replace(">", "").ToString()

' String.Replace version:
Return text.Replace("<", "").Replace(">", "")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜