热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

是否有更快的方式来循环数千个项目?-Isthereafasterwaytoloopthroughthousandsofitems?

SayIhaveabytearraywith100,000bytesinit.Iwanttoconverteachbyteintoitstextualrepre

Say I have a byte array with 100,000 bytes in it. I want to convert each byte into its textual representation of itself. For example:

假设我有一个包含100,000个字节的字节数组。我想将每个字节转换为其自身的文本表示。例如:

byte[] b = new byte[55000];

for(int i = 0; i 

The above code takes around 35 seconds to complete, is there some way I could cut that down to around 5 seconds?

上面的代码需要大约35秒才能完成,有什么方法可以将其减少到大约5秒钟吗?

3 个解决方案

#1


4  

As mentioned in my comment I would suggest removing the Console.WriteLine() method. I would also suggest that it be avoided in loops. Typically if you want to see what is being processed you would use either the Debug.WriteLine() (MSDN) or set a breakpoint (even a conditional breakpoint if you have a specific case that isn't working right). If you need to return the data then again i would suggest using a string builder:

正如我在评论中提到的,我建议删除Console.WriteLine()方法。我还建议在循环中避免它。通常,如果要查看正在处理的内容,可以使用Debug.WriteLine()(MSDN)或设置断点(如果您的特定情况不正常,则甚至是条件断点)。如果您需要再次返回数据,我建议使用字符串生成器:

byte[] b = new byte[55000];
StringBuilder myStringBuilder = new StringBuilder();

for(int i = 0; i 

#2


3  

one thing I fond is Write a Parallel.For Loop with might do faster thing than right now..

我喜欢的一件事是写一个Parallel.For循环,可能比现在更快。

    static void Main()
    {
        int[] nums = Enumerable.Range(0, 1000000).ToArray();
        long total = 0;

        // Use type parameter to make subtotal a long, not an int
        Parallel.For(0, nums.Length, () => 0, (j, loop, subtotal) =>
        {
            subtotal += nums[j];
            return subtotal;
        },
            (x) => Interlocked.Add(ref total, x)
        );

        Console.WriteLine("The total is {0}", total);
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

#3


-1  

Profile your code to see what method is taking the most time. Focus your optimization efforts on that method.

描述您的代码,看看哪种方法花费的时间最多。将优化工作集中在该方法上。


推荐阅读
author-avatar
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有