更快地打印控制台字符 [英] print console characters faster

查看:54
本文介绍了更快地打印控制台字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受数字的函数,该函数会将其转换为如下所示的数字的5x7图形表示形式:

I have a function that accepts a number which will convert it to a 5x7 graphic representation of digits like this:

Console.WriteLine(" ███ ");  // byte: 0000 1110
Console.WriteLine("█   █");  //       0001 0001
Console.WriteLine("█   █");  //       0001 0001
Console.WriteLine("█   █");  //       0001 0001
Console.WriteLine("█   █");  //       0001 0001
Console.WriteLine("█   █");  //       0001 0001
Console.WriteLine(" ███ ");  //       0000 1110

有人告诉我使用字节数组可以更快地完成操作.这基本上就是我所做的:

I was told it can be done faster using byte arrays. This is basically what I did:

byte[] data = new byte[] { 14, 17, 17, 17, 17, 17, 14 };
BitArray bitData = new BitArray(data);


int bitCounter = 0;
foreach (bool bit in bitData)
{ 
  if (bit)   
    Console.Write("█");
  else 
    Console.Write(" ");
  bitCounter++;
  if (bitCounter>7)
  { 
    bitCounter=0;
    Console.WriteLine();
  }
}

这比开始时要慢,所以我不能使用它.谁能告诉我更好的方法?

This is slower than what is started with so I can't use it. Can anyone show me a better way?

更新:StringBuilder确实有帮助,但是它会比我原来的代码慢一些.它仍然基本上在控制台中使用了7次write命令,这让我很慢.我尝试使用\ n仅使用1个写命令,但是我需要缩进下一行而不擦除缩进空格内的内容.

Update: StringBuilder does help, but it will be a bit slower than the original code I had. Its still basically using the write command 7 times in the console is slowing me down. I tried using using just 1 write command using \n, but I need to indent the next line without erasing inside the indented spaces.

推荐答案

I最小化了IO.这是下面的版本,仅在最后进行控制台调用.

I Minimized IO. Here is a version below that makes console calls only at the end.

        var stringBuilder = new StringBuilder();
        bitCounter = 0;
        foreach (bool bit in bitData)
        {                
            if (bit)
                stringBuilder.Append("█");
            else
                stringBuilder.Append(" ");
            bitCounter++;
            if (bitCounter > 7)
            {
                bitCounter = 0;
                Console.WriteLine(stringBuilder.ToString());
                stringBuilder.Clear();
            }
        }

这篇关于更快地打印控制台字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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