Convert.ToBase64String更快的替代品?

时间:2011-04-26 00:14:27

标签: c# .net performance

使用.NET Framework;有Convert.ToBase64String(byteArray)的更快替代方案吗?

更新

为了给出更多进一步的背景信息,我正在为发件人不同的电子邮件编码文件附件,因此我将在循环中为此编码相当多的(假设为1000)> 1MB文件。

简化示例:

for(int i = 0; i < 1000; i++) {
    var file = System.IO.File.ReadAllBytes("c:\\temp\\clientfile" + i + ".pdf");
    System.IO.File.WriteAllText("c:\\emailsendtest\\test" + i + ".tmp", Convert.ToBase64String(file));
}

2 个答案:

答案 0 :(得分:4)

以下是一些比较两种方法的数据(Convert ...和Cryptography ...)。我运行了200次测试,写出100万字节到一个新的1 MB文件。看起来Convert.ToBase64方法平均比加密方法快七倍左右。测试运行的直方图如下:

enter image description here

如果有人有兴趣验证我的结果 - 这是我的测试代码:

private static void Test()
{

    Random myRand = new Random();

    List<TimeSpan> convert64Times = new List<TimeSpan>();
    List<TimeSpan> cryptoTimes = new List<TimeSpan>();
    Stopwatch theTimer = new Stopwatch();



    for (int i = 0; i < 200; i++)
    {

        byte[] randBytes = new byte[1000000];
        myRand.NextBytes(randBytes);

        string filePrefix = @"C:\Temp\file";


        // test encode with convert to base 64
        theTimer.Start();
        EncodeWithConvertToBase64(randBytes,filePrefix+i+"convert.txt");
        theTimer.Stop();
        convert64Times.Add(theTimer.Elapsed);
        theTimer.Reset();


        // test encode with crypto
        theTimer.Start();
        EncodeWithCryptoClass(randBytes,filePrefix+i+"crypto.txt");
        theTimer.Stop();
        cryptoTimes.Add(theTimer.Elapsed);
        theTimer.Reset();

    }
}



private static void EncodeWithConvertToBase64(byte[] inputBytes, string targetFile)
{
    string fileString = Convert.ToBase64String(inputBytes);

    using (StreamWriter output = new StreamWriter(targetFile))
    {
        output.Write(fileString);
        output.Close();
    }
}

private static void EncodeWithCryptoClass(byte[] inputBytes, string targetFile)
{

    FileStream outputFileStream =
        new FileStream(targetFile, FileMode.Create, FileAccess.Write);

    // Create a new ToBase64Transform object to convert to base 64.
    ToBase64Transform base64Transform = new ToBase64Transform();

    // Create a new byte array with the size of the output block size.
    byte[] outputBytes = new byte[base64Transform.OutputBlockSize];



    // Verify that multiple blocks can not be transformed.
    if (!base64Transform.CanTransformMultipleBlocks)
    {
        // Initializie the offset size.
        int inputOffset = 0;

        // Iterate through inputBytes transforming by blockSize.
        int inputBlockSize = base64Transform.InputBlockSize;

        while (inputBytes.Length - inputOffset > inputBlockSize)
        {
            base64Transform.TransformBlock(
                inputBytes,
                inputOffset,
                inputBytes.Length - inputOffset,
                outputBytes,
                0);

            inputOffset += base64Transform.InputBlockSize;
            outputFileStream.Write(
                outputBytes,
                0,
                base64Transform.OutputBlockSize);
        }

        // Transform the final block of data.
        outputBytes = base64Transform.TransformFinalBlock(
            inputBytes,
            inputOffset,
            inputBytes.Length - inputOffset);

        outputFileStream.Write(outputBytes, 0, outputBytes.Length);

    }

    // Determine if the current transform can be reused.
    if (!base64Transform.CanReuseTransform)
    {
        // Free up any used resources.
        base64Transform.Clear();
    }

    // Close file streams.

    outputFileStream.Close();
}

答案 1 :(得分:1)

假设您的文件附件是作为流读入的,建议您使用System.Security.Cryptography中的ToBase64Transform类而不是Convert类。

可以在该页面上找到一个完整的示例,该示例从输入文件中读取并写回编码文件。

您还应该看看JMarsch的示例,找到here

相关问题