在进一步处理之前实现比较两个字符串的逻辑



我正在尝试将一些逻辑合并到应用程序中,以提高其性能,但我根本无法实现它的好方法。所以我有一组 json 文件,我从中反序列化,所有这些文件都具有相同的结构。

{
urlSouce": """,
"info": [
{
"id": ""
}
]
}

因此,每次我反序列化文件时,我都会在变量中urlSOurce并将该值用于API请求。但是,我已经了解大多数时候这个urlSource是相同的,因此不需要继续发送API请求并影响性能,这就是为什么我首先要检查来自当前反序列化文件的urlSource是否与以前的文件相同。

如果是这样,则无需再次发送 API 请求。我知道我可以添加一个布尔标志来添加这个逻辑,但我想不出哪里是保存它的最佳位置。

为了演示我正在做的事情,我有以下代码。如果有人对需要做什么有任何想法,请帮助我

string previousUrl;
string currentURL;
bool isValueChanged;
currentURL = "test1.com"; //the new URL populated from the deserialized JSON
previousUrl = "test2.com"; //the previously deserialized URL of the file before this

在这里,我对任何反序列化都没有问题

我遇到的问题是我如何跟踪以前的URl值?以及如何操纵布尔标志?

听起来您想在处理字符串之前验证以前是否未使用过它。

如果是这种情况,你可以简单地将"使用过的"字符串存储在一个Dictionary中,字符串作为Key,处理的结果作为Value,然后检查字典是否已经包含任何新字符串的Key在处理它们之前。

下面的方法采用要处理的string和指定是否使用缓存结果(如果存在(的bool。如果string不包含在字典中,或者用户指定useCache = false,则处理字符串并将其保存在字典中(与结果一起(,并返回结果。否则,将立即返回该字符串的缓存结果。

private readonly Dictionary<string, string> cachedResults = new Dictionary<string, string>();
public string GetApiResult(string uri, bool useCachedResult = true)
{
// If we've already encountered this string, return the cached result right away
if (useCachedResult && cachedResults.ContainsKey(uri)) return cachedResults[uri];
// Process the string here
var result = MakeAPICall(uri);
// Save it, along with the result, in our dictionary
cachedResults[uri] = result;
// Return the result
return result;
}

听起来我误解了这个问题。如果您只是尝试确定新字符串是否与遇到的最后一个字符串匹配,那么这也非常简单:

private string cachedUri;
private string cachedResult;
public string GetApiResult(string uri, bool useCachedResult = true)
{
// If we've already encountered this string, return the cached result right away
if (useCachedResult && uri == cachedUri) return cachedResult;
// Process the string here
var result = MakeAPICall(uri);
// Save it, along with the result, in our fields
cachedUri = uri;
cachedResult = result;
// Return the result
return result;
}

我会使用MemoryCache(或只是Dictionary(将 Url 作为键,将响应的结果作为值,但如果通常只有一个 url 变量就足够了:

string previousUrl = null;
string previousValue = null;
string currentURL;
bool isValueChanged;
while (…)
{
string result = null;
currentURL = "test1.com"; //the new URL populated from the deserialized JSON
if (previousUrl != currentUrl)
{
previousResult = GetTheData(currentUrl);
previousUrl = currentUrl;
}
result = previousResult;
// process result for currentUrl 
}

最新更新