为什么在C#这CRC32实现这么慢? [英] Why is this CRC32 implementation in C# so slow?

查看:1660
本文介绍了为什么在C#这CRC32实现这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的函数来计算在VS2008文件的CRC32,.NET 3.5的项目:

I'm using the following function to compute the CRC32 of a file in a VS2008, .NET 3.5 project:

public UInt32 ComputeHash(System.IO.Stream stream)
{
    unchecked
    {
        const int BUFFER_SIZE = 1024;

        UInt32 crc32Result = 0xFFFFFFFF;
        byte[] buffer = new byte[BUFFER_SIZE];
        int count = stream.Read(buffer, 0, BUFFER_SIZE);

        while (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                crc32Result = ((crc32Result) >> 8) ^ _crc32Table[(buffer[i]) ^ (crc32Result) & _LOOKUP_TABLE_MAX_INDEX];
            }
            count = stream.Read(buffer, 0, BUFFER_SIZE);
        }

        return ~crc32Result;
    }
}

有关为了简洁起见,我已经离开指出构建查找表(_crc32Table)的功能。该表是UInt32的阵列,当类被实例化构建,并含有256个值(256也是_LOOKUP_TABLE_MAX_INDEX + 1的值)。

For the sake of brevity, I have left out the function that builds the lookup table (_crc32Table). The table is an array of UInt32, is built when the class is instantiated, and contains 256 values (256 is also the value of _LOOKUP_TABLE_MAX_INDEX + 1).

我已经运行比较这对MD5CryptoServiceProvider和SHA1CryptoServiceProvider ComputeHash函数的一些标准,他们快得多。该MD5函数超过两倍的速度和SHA1哈希约35%的速度。有人告诉我,CRC32快,但是这不是我所看到的。

I have run some benchmarks comparing this to the MD5CryptoServiceProvider and SHA1CryptoServiceProvider ComputeHash functions and they are much faster. The MD5 function is over twice as fast and the SHA1 hash is about 35% faster. I was told CRC32 is fast, but that's not what I'm seeing.

难道我错了我的假设?这是可以预期的还是有这个算法中的一个漏洞?

Am I mistaken in my assumptions? Is this to be expected or is there a flaw in this algorithm?

推荐答案

您是在比较你的code内置函数和问,为什么他们更快。什么,你需要做的是找到源内置函数。他们如何工作?看看有什么不同。

You are comparing your code to built in functions and asking why they are faster. What you need to do is find the source for the built in functions. How do they work? See what's different.

betcha当内置的函数调用了一个本地库,​​并没有给托管内存框架内运行作弊。

Betcha the built in functions call out to a native library and cheat by not having to run inside the managed memory framework.

这篇关于为什么在C#这CRC32实现这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆