Skip to content

Commit 9d02bba

Browse files
authored
Improve to avoid heap allocation (#60)
1 parent 3eaeb11 commit 9d02bba

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

kbsquaredmatrix.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ type SquaredMatrixKeyboard struct {
1414
Pins []machine.Pin
1515
cycleCounter []uint8
1616
debounce uint8
17+
18+
colsBuf []int
1719
}
1820

1921
func (d *Device) AddSquaredMatrixKeyboard(pins []machine.Pin, keys [][]Keycode) *SquaredMatrixKeyboard {
@@ -41,6 +43,7 @@ func (d *Device) AddSquaredMatrixKeyboard(pins []machine.Pin, keys [][]Keycode)
4143
callback: func(layer, index int, state State) {},
4244
cycleCounter: cycleCnt,
4345
debounce: 8,
46+
colsBuf: make([]int, len(pins)),
4447
}
4548

4649
d.kb = append(d.kb, k)
@@ -59,7 +62,7 @@ func (d *SquaredMatrixKeyboard) Callback(layer, index int, state State) {
5962

6063
func (d *SquaredMatrixKeyboard) Get() []State {
6164
c := int(0)
62-
cols := []int{}
65+
cols := d.colsBuf[:0]
6366
for i := range d.Pins {
6467
for j := range d.Pins {
6568
d.Pins[j].Configure(machine.PinConfig{Mode: machine.PinInputPullup})

keyboard.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ type Device struct {
3939
combosReleased []uint32
4040
combosKey uint32
4141
combosFounds []Keycode
42+
43+
pressToReleaseBuf []uint32
44+
noneToPressBuf []uint32
4245
}
4346

4447
type KBer interface {
@@ -83,6 +86,9 @@ func New() *Device {
8386
combosReleased: make([]uint32, 0, 10),
8487
combosKey: 0xFFFFFFFF,
8588
combosFounds: make([]Keycode, 10),
89+
90+
pressToReleaseBuf: make([]uint32, 0, 20),
91+
noneToPressBuf: make([]uint32, 0, 20),
8692
}
8793

8894
SetDevice(d)
@@ -192,7 +198,7 @@ func (d *Device) GetMaxKeyCount() int {
192198
}
193199

194200
func (d *Device) Tick() error {
195-
pressToRelease := []uint32{}
201+
pressToRelease := d.pressToReleaseBuf[:0]
196202

197203
select {
198204
case <-d.flashCh:
@@ -210,7 +216,7 @@ func (d *Device) Tick() error {
210216
}
211217

212218
// read from key matrix
213-
noneToPress := []uint32{}
219+
noneToPress := d.noneToPressBuf[:0]
214220
for kbidx, k := range d.kb {
215221
state := k.Get()
216222
for i := range state {

0 commit comments

Comments
 (0)