我遇到了在列表中查找项目的编程代码。当我问为什么要使用这个代码时,他们说因为这样可以更快地运行。
这是真的吗?
这是真的吗?
public static Location GetRecordById(this List<Location> records, int? id)
{
if (id == null) return null;
int position = records.BinarySearch(new() { Id = (int)id });
return position >= 0 ? records[position] : null;
}
比……更快的方式
public static Location GetRecordById(this List<Location> records, int? id)
{
if (id == null) return null;
return records.FirstOrDefault( w => w.Id == id );
}
O(log n)
,而线性查找的时间复杂度为O(n)
。然而,二分查找假定集合已经排序,如果没有排序,您需要考虑排序集合所需的时间。 - MatthewDictionary<int, Location>
,并使用TryGetValue
- 这样它就是O(1)
。 - Marc GravellDictionary<int, Location>
更快,但代价是增加了内存占用(每个项大约多12字节)。 - Theodor Zoulias