简体   繁体   English

有什么方法可以加快c#中的for循环吗?

[英]Is there any way to speed up the for loop in c#?

I have a situation like 我有这样的情况

for(int count = 0; count <= GetNumberOfRecordsFromFile(path) ; count++)
{
    //do stuff with count                    
}

In this loop GetNumberOfRecordsFromFile(path) method returns the number of records present in the file in hundreds of thousands or more.The issue is that when the for loop is running to do calculation with count , it is slowing down but works fine..I also tried using of ParallelFor loop but it creates problem in calculation...Is there any equivalent way to run the for loop to be faster...? 在此循环中, GetNumberOfRecordsFromFile(path)方法返回文件中存在的数十万或更多的记录数。问题是,当for循环运行使用count进行计算时,它的速度变慢但可以正常工作。也尝试使用ParallelFor循环,但是它在计算中产生了问题...是否有任何等效的方法可以更快地运行for循环...?

You can simply calculate it once, store in variable and reuse: 您只需计算一次,存储在变量中并重复使用:

int numberOfRecords = GetNumberOfRecordsFromFile(path);
for(int count = 0; count <= numberOfRecords; count++)
{
    //do stuff with count                    
}

Now, there is definitely no way to "speed up" this loop. 现在,绝对没有办法“加快”这个循环。 It is as simple as possible. 它尽可能简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM