【问题标题】:Converting byte[] to String with new Operator(performance)使用新运算符将字节 [] 转换为字符串(性能)
【发布时间】:2014-05-21 14:38:13
【问题描述】:

基于以下问题,

http://stackoverflow.com/questions/23753342/java-memory-allocation-for-local-variables

我使用 SerialPortEvent 从串口读取数据,

public String logtext = ""; 
public void serialEvent(SerialPortEvent evt) {

if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
    try {
        StringBuilder sBuilder = new StringBuilder();
        int length = input.available();
        byte[] array = new byte[length];
        int numBytes = input.read(array);
        for (byte b : array) {
          logText = new String(new byte[] {b});                 
          sBuilder.append(logText);
        }
       //Finally i append the StringBuilder to JtextPane
       .......
       ......
        }

创建 new String() 每次调用 serialEvent 时都会创建新实例,这会增加内存使用量。在某些情况下,此 serialEvent 将每秒调用一次。

有没有其他有效的方法可以在不使用 new 操作符的情况下做到这一点?

请帮忙

【问题讨论】:

  • 阅读一下 String 的文档吧?

标签: java string memory bytearray


【解决方案1】:

您不需要一次只做一个字节。我会一次完成所有字节。

int length = input.available();
byte[] array = new byte[length];
String logText = new String(array, 0); // assume ISO-8859-1 encoding

【讨论】:

  • 是的,我会这样做,但是在我的字节数组中,我有换行符和响铃 ascii 的 ASCII 值。为了删除它,如果字节数组内容等于 ascii 不显示,我会这样做在 JtextPane 中。有什么方法可以使用您提到的代码从字符串中删除 ascii。
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 2019-03-24
  • 2019-10-10
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多