[英]Fastest way to get subset of array of items into a string?
我的方法接收一個位置數組,用於連接另一個數組中的某些項。 目前,我正在遍歷這些位置並將它們添加到StringBuilder
,但有更快的方法嗎? C#是否有一些方法使用本機代碼(類似於Java的System.arraycopy
)來做更快的“循環”?
基本理念:
int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };
StringBuilder concat = new StringBuilder();
for ( int i = 0; i < positions.length; i++ )
{
concat.Append(values[positions[i]]);
concat.Append(",");
}
有什么更快的嗎?
嘗試:
int[] positions = new int[] { 2, 5, 7 };
string[] values = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };
var res = string.Join(",", positions.Select(f => values[f]));
據我所知,for循環是c#中最快的循環之一,在這種情況下,你的代碼不能並行。 所以簡短的答案是否定的,它不能更快。
很長的答案,雖然沒有性能改進,但這里不需要使用字符串構建器,只需在沒有字符串構建器的情況下附加。 只是delcare concat作為一個字符串,你可以在for循環中做這樣的事情
concat += $"{values[positions[i]]},"
有一點需要注意,雖然你可能已經考慮到這一點,位置0將返回值“三”記住在c#數組從0開始
編輯:從用戶史蒂夫指出我做了一個小嘗試和錯誤,我發現最快的方法就是這樣做
string concat3 = "";
for (int i = 0; i < positions.Length; i++)
{
concat3 += values[positions[i]] + ", ";
}
Console.WriteLine(stop.ElapsedTicks);
但我們正在談論其中3個差異的5個滴答(每個試驗約20次)所以我甚至不認為這是性能下降
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.