简体   繁体   English

在Java中有效串联2个字节

[英]Concatenating 2 bytes in Java efficiently

I am working on a program where I am trying to reduce the amount of memory allocated, I previously use to concatenate strings but the problem was that I do this process several million times and the more I did it the longer it took to allocate these strings. 我正在一个程序中尝试减少分配的内存量,我以前使用它来连接字符串,但是问题是我执行了此过程数百万次,并且执行的次数越多,分配这些字符串所花费的时间就越长。 Instead now I am trying work with bytes. 相反,现在我正在尝试使用字节。 I want to do something like this: 我想做这样的事情:

byte[] arr = new byte[5];
byte cat = arr[0] + arr[1]  //this addition would give me an error obviously. It's for demostration purposes

System.out.println(cat);

I just want to take the first byte and put the second one right after it without using any form of String Class as it requires more overhead to concatenate strings as such. 我只想获取第一个字节,然后将第二个字节放在其后,而不使用任何形式的String Class,因为这样串联字符串需要更多的开销。 Is there a way I can do this with minimal operations? 有什么办法可以用最少的操作做到这一点?

Create a new output byte array of the size equal to the sum of all your bytes that are to concatenated in a new byte array using System.arraycopy() 使用System.arraycopy()创建一个新的输出字节数组,该数组的大小等于要在新字节数组中串联的所有字节的总和。

As System.arraycopy() is native call, it will be certainly faster than String concatenation. 由于System.arraycopy()是本机调用,因此肯定比String串联更快。

If you want to "concatenate" two or more bytes, into a new byte array, just use the array initializer syntax: 如果要将两个或多个字节“连接”成一个新的字节数组,只需使用数组初始化程序语法:

byte a = 1;
byte b = 42;
byte c = 99;

byte[] cat = {a,b,c};

System.out.println(Arrays.toString(cat)); // prints: [1, 42, 99]

Your example is however more akin to a substring() call, and for that you should use Arrays.copyOfRange() , eg 但是,您的示例更类似于substring()调用,为此,您应该使用Arrays.copyOfRange() ,例如

byte[] arr = {5,4,3,2,1};

byte[] cat = Arrays.copyOfRange(arr, 0, 2);

System.out.println(Arrays.toString(cat)); // prints: [5, 4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM