使用LINQ解析字符串效率高吗?
在过去的几周里,我一直在使用 LINQ,以至于我不得不编写一个单行函数来删除 <<和>从字符串中,我发现我已将其编写为 LINQ 查询:
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
我的问题是,是像上面那样使用 LINQ 还是像我一直所做的那样使用 StringBuilder 更好,如下所示:
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
两者都有效,第二个是更容易阅读,但第一个设计用于对数组和其他枚举执行查询。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更加简单。
或者:
很难说选项 A、B 或 C 是否比其他选项更快,因为选项 A 可能在小字符串上更好,而选项 B 可能在长字符串上更好,等等。
Is much more straightforward.
Or:
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.
就功能而言,任何一个都应该很好。第一个效率不高。
ToArray
调用所做的工作远多于必要的工作(如果您使用的是 .NET 4.0,则无论如何都不需要),而ToCharArray
不需要打电话。基本上,输入字符串中的字符被迭代的次数比它们需要的要多得多,并且额外的数组被多余地分配。我不会说这特别重要;但你问的是效率,所以我才提到它。
第二个对我来说似乎很好。请注意,如果您想采用单行路线,您仍然可以使用 StringBuilder 来实现,并且我认为仍然有比 LINQ 版本更简洁的东西(尽管我没有计算字符数)。不过,我不清楚这是否优于更直接的 String.Replace 选项:
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 theToCharArray
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 directString.Replace
option is kind of unclear to me, though: