我正在尝试从object[]
列表中检索ID列表。这是我的代码:
private static List<int> getReceivedIds(object[] objectList)
{
var received = new List<int>();
foreach (object[] b in objectList)
{
if (b != null)
{
received.Add(int.Parse((b[0].ToString())));
}
}
return received;
}
我正在为此代码寻找性能优化的解决方案。
我将代码更改为:
private static List<int> getReceivedIds2(object[] objectList)
{
var received = new List<int>();
foreach (object[] b in objectList)
{
if (b != null)
{
received.Add((int)b[0]);
}
}
return received;
}
我还比较了LINQ查询和foreach
语句性能,结果如下:
Performance test results
测试显示foreach
语句比LINQ快6倍。
任何人都可以提高此代码的性能吗?
以下是我测试的代码:
class Program
{
static void Main(string[] args)
{
for (int test = 0; test < 100; test++)
{
object[] objectList = new object[1000];
Random rnd = new Random();
for (int i = 0; i < 1000; i++)
{
objectList[i] = new object[] { rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000) };
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 1; i < 100000; i++)
{
getReceivedIds(objectList);
}
stopWatch.Stop();
var t1 = stopWatch.Elapsed.TotalMilliseconds;
stopWatch.Restart();
for (int i = 1; i < 100000; i++)
{
getReceivedIds2(objectList);
}
stopWatch.Stop();
var t2 = stopWatch.Elapsed.TotalMilliseconds;
Console.WriteLine(string.Format("LINQ: {0} - ForEach: {1}", t1, t2));
}
}
private static List<int> getReceivedIds(object[] objectList)
{
List<int> received = objectList.Cast<object[]>()
.Where(b => b != null)
.Select(b => (int)b[0]) // or Convert.ToInt32(b[0])
.ToList();
return received;
}
private static List<int> getReceivedIds2(object[] objectList)
{
var received = new List<int>();
foreach (object[] b in objectList)
{
if (b != null)
{
received.Add((int)b[0]);
}
}
return received;
}
}
答案 0 :(得分:2)
如果object[]
中的第一项实际上是int
,您不需要解析它,您可以投出它。如果需要,可以使用此LINQ查询:
List<int> received = objectList.Cast<object[]>()
.Where(b => b != null)
.Select(b => (int)b[0]) // or Convert.ToInt32(b[0])
.ToList();
答案 1 :(得分:1)
试试这个:
int[] resultArray = Array.ConvertAll(inputArray, x => Convert.ToInt32(x));
注意:确保值为int。
供参考:msdn link for ConvertAll()