【问题标题】:Optimizing .NET function in terms of search index usage在搜索索引使用方面优化 .NET 功能
【发布时间】:2015-03-21 09:39:17
【问题描述】:

我编写了一个函数来搜索数组以查找特定单词的出现。该函数接受一个文本行数组和一个它必须搜索的目标关键字,并返回一个包含目标单词的 ines 数组列表。例如如果数组是(每一行都是数组的下标):

测试 .net 应用程序 棕色的大猫 示例应用程序 搜索索引优化 寻找猫 粉红色的大大象

函数调用是FindLinesInArray(arr, "cat"),那么函数会返回两行数组列表:

棕色的大猫 寻找猫

函数如下:

Function FindLinesInArray(ByRef arr() As String, ByVal target As String) As ArrayList
    Dim idx As Integer
    Dim temp As String = ""
    Dim alist As ArrayList = New ArrayList()

    Try
        For idx = 0 To arr.Length - 1
            If arr(idx).ToString().ToLower().IndexOf(target) <> -1 Then
                temp = arr(idx).ToString().ToLower().Trim()
                alist.Add(temp)
            End If
        Next
    Catch ex As Exception
        MsgBox(ex.Message & " - " & ex.StackTrace)
    End Try

    Return alist

End Function

我的问题是如何根据搜索索引的使用来优化此功能。我正在运行的程序在大型数组上多次调用此函数,我想知道是否有更好的方法来执行此操作

【问题讨论】:

  • 你有很多不同的大数组要搜索吗?还是您总是使用同一个数组来搜索许多不同的目标?
  • 基本上我有许多不同的大数组和一个小的搜索值数组。在我的示例中,我曾经搜索过“cat”一词,但实际上有一个包含 5 个或更多“cat”这个词的变体的整个数组要搜索。它可以是“cat”,或“cats”或“c at”或“cat ts”或“cat s”,只是为了给你一个例子。所以我有一个数组 arrtarget 作为 string()={"cat","cats","c at", "cat ts", "cat s"} 然后是一些大数组,我需要搜索其中的每一个大型数组并找到包含单词“cat”的任何变体的所有行

标签: .net arrays performance search optimization


【解决方案1】:

这是c#
我是凭记忆做的,所以它可能有一些语法错误

public class SearchLine 
{
    private HashSet<string> words;
    public void ContainsWords (HashSet<string> FindWords)
    {
        if (words == null)
        {
            words = new HashSet<string>();
            foreach (string s in Line.Split(" "))
            {
               if(!string.IsNullOrEmpty(s))
                  words.Add(s.Trim());
            }
        }
        return FindWords.Overlaps(words);
    }
    public string Line { get; private set;
    public SearchLine(string line) 
    {
        Line = line;
    }
}

【讨论】:

  • 输入必须是数组而不是哈希集。我需要改进现有代码
  • 究竟为什么输入需要是数组而不是哈希集?它是一组要匹配的单词。 HashSet Overlaps 快速冒烟 - 数组没有 Overlaps。您可以从数组中创建 HashSet。
  • 因为这是我无法改变的。我必须使用我所拥有的,这是一个数组
  • 真的,不能创建SearchLine数组吗? SearchLine 将字符串作为 ctor。为什么不一次(快速)测试一整套单词而不是一次测试一个?
  • Blam,我在问是否有办法改进我提出的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2011-05-14
相关资源
最近更新 更多