Skip to content

Commit

Permalink
perf[protocol]: memory copy for int list
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysunxiao committed Nov 17, 2023
1 parent 72bc89b commit 4881edb
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions protocol/src/main/java/com/zfoo/protocol/buffer/CustomByteBuf.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@

package com.zfoo.protocol.buffer;

import com.zfoo.protocol.collection.ArrayListInt;
import com.zfoo.protocol.collection.ArrayUtils;
import com.zfoo.protocol.collection.CollectionUtils;
import io.netty.buffer.ByteBuf;

import java.nio.ByteBuffer;
import java.util.List;

/**
* 自定义协议格式,可以针对某些特定场景对做特定优化
Expand Down Expand Up @@ -55,7 +58,7 @@ public static int[] readIntArraySimple(ByteBuf byteBuf) {
}

// 针对于int数组提高性能的复杂方式
public static void writeIntArrayComplex(ByteBuf byteBuf, int[] array) {
public static void writeIntArrayMemoryCopy(ByteBuf byteBuf, int[] array) {
if (array == null) {
byteBuf.writeByte(0);
return;
Expand All @@ -69,7 +72,7 @@ public static void writeIntArrayComplex(ByteBuf byteBuf, int[] array) {
byteBuf.writeBytes(byteBuffer);
}

public static int[] readIntArrayComplex(ByteBuf byteBuf) {
public static int[] readIntArrayMemoryCopy(ByteBuf byteBuf) {
var length = ByteBufUtils.readInt(byteBuf);
var byteBuffer = ByteBuffer.allocate(length * 4);
byteBuf.readBytes(byteBuffer);
Expand All @@ -80,4 +83,16 @@ public static int[] readIntArrayComplex(ByteBuf byteBuf) {
return ints;
}

public static void writeIntListMemoryCopy(ByteBuf byteBuf, List<Integer> list) {
if (list == null) {
byteBuf.writeByte(0);
return;
}
var array = ArrayUtils.intToArray(list);
writeIntArrayMemoryCopy(byteBuf, array);
}

public static List<Integer> readIntListMemoryCopy(ByteBuf byteBuf) {
return new ArrayListInt(readIntArrayMemoryCopy(byteBuf));
}
}

0 comments on commit 4881edb

Please sign in to comment.