【问题标题】:vb.net string.split vs substring.lastindexof - which is faster or 'better'vb.net string.split vs substring.lastindexof - 更快或“更好”
【发布时间】:2016-07-28 12:38:51
【问题描述】:

我有一个循环读取大量字符串,每个字符串都包含由字符 (¥) 分割的信息。 对于这个循环,我只需要最终值,我知道它的索引。我想知道使用 string.split 还是使用 substring.lastindexof 更好。

如果有帮助,拆分的索引是 8。

这样会更快。 另外,我对 char 的选择对拆分有影响吗? (例如¥ vs` vs ")

谢谢。

【问题讨论】:

  • lastindexof 应该更快,因为它从末尾搜索。
  • 它们是两个不同的东西。 Split 分割字符串,LastIndexOf 只是告诉你一个字符在哪里。
  • 如果你已经知道你感兴趣的位置,那么当你只需要最后一个时,不需要使用 split 并创建一个字符串数组,只需使用 substring
  • 嗨 Plutonix。抱歉,我的意思是使用带有 lastindexof 的子字符串
  • 这是你可以自己测试的东西。每次运行一百万次,比较结果。

标签: vb.net string split substring lastindexof


【解决方案1】:

人们似乎倾向于 substring(lastindexof) 而不是 string.split - 我只是做了一个小的计时器测试,看看哪个更快。

For count As Integer = 0 To existing.Count - 1
        If File.Exists(existing(count).Substring(existing(count).LastIndexOf("¥") + 1)) Then 'File.Exists(existing(count).Split(CChar("¥"))(8)) Then
            outputfile.Add(existing(count))
        Else
            outputfile.Add(String.Empty)
        End If
        Next

现在这种情况下的字符串用于 mp3 标签信息和路径。它们通常看起来像

"Opeth¥Apostle In Triumph Demo¥Apostle In Triumph Demo Part 1¥1:41¥1¥1984¥Progressive Death/Doom/Folk Metal¥¥C:\Users\black\Music\Opeth\Apostle In Triumph Demo \Opeth - Apostle In Triumph Demo Part 1.mp3"

因此它通过 8022 个字符串检查文件是否存在(使用 existing(count).split(cchar("¥"))(8))existing(count).Substring(existing(count).lastindexof("¥") + 1)),然后将值放入列表中。

在我测试这两种方法的 10 次中,拆分方法总是更快 - 平均快 32 毫秒,或快 2.27%。

我做错了吗?

【讨论】:

  • 您正在测量File.Exists 的性能。删除它,只测量 LastIndexOfSplit
  • 如果您不知道,"¥"cCChar("¥") 相同。
猜你喜欢
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
相关资源
最近更新 更多