Skip to content

Commit 7f8e211

Browse files
committed
Reduce memory alloc in read thread
1 parent 037aad1 commit 7f8e211

File tree

4 files changed

+8
-9
lines changed

4 files changed

+8
-9
lines changed

android/src/main/java/com/bastengao/serialport/SerialPortApiModule.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,9 @@ public static byte[] hexStringToByteArray(String s) {
152152

153153
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
154154

155-
public static String bytesToHex(byte[] bytes) {
156-
char[] hexChars = new char[bytes.length * 2];
157-
for (int j = 0; j < bytes.length; j++) {
155+
public static String bytesToHex(byte[] bytes, int length) {
156+
char[] hexChars = new char[length * 2];
157+
for (int j = 0; j < length; j++) {
158158
int v = bytes[j] & 0xFF;
159159
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
160160
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];

android/src/main/java/com/bastengao/serialport/SerialPortWrapper.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,15 @@ public SerialPortWrapper(String path, SerialPort serialPort, final EventSender s
3737
this.readThread = new Thread(new Runnable() {
3838
@Override
3939
public void run() {
40+
byte[] buffer = new byte[64];
4041
while (!closed.get()) {
4142
try {
4243
int size;
43-
byte[] buffer = new byte[64];
4444
if (in == null) return;
4545
size = in.read(buffer);
4646
if (size > 0) {
4747
WritableMap event = Arguments.createMap();
48-
byte[] data = Arrays.copyOf(buffer, size);
49-
String hex = SerialPortApiModule.bytesToHex(data);
48+
String hex = SerialPortApiModule.bytesToHex(buffer, size);
5049
event.putString("data", hex);
5150
event.putString("path", path);
5251
sender.sendEvent(DataReceivedEvent, event);

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "react-native-serial-port-api",
33
"title": "React Native Serial Port API",
4-
"version": "1.4.0-rc.2",
4+
"version": "1.4.0-rc.3",
55
"description": "React Native Serial Port API",
66
"main": "lib/commonjs/index.js",
77
"react-native": "src/index.ts",

0 commit comments

Comments
 (0)