Skip to content

Commit

Permalink
Pre-allocate geohash slice memory
Browse files Browse the repository at this point in the history
  • Loading branch information
Orlion authored and HDT3213 committed Feb 17, 2023
1 parent d77f08c commit e5068f7
Showing 1 changed file with 4 additions and 16 deletions.
20 changes: 4 additions & 16 deletions lib/geohash/geohash.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package geohash

import (
"bytes"
"encoding/base32"
"encoding/binary"
)
Expand All @@ -18,36 +17,25 @@ func encode0(latitude, longitude float64, bitSize uint) ([]byte, [2][2]float64)
{-90, 90}, // lat
}
pos := [2]float64{longitude, latitude}
hash := &bytes.Buffer{}
bit := 0
hash := make([]byte, bitSize>>3)
var precision uint = 0
code := uint8(0)
for precision < bitSize {
for direction, val := range pos {
mid := (box[direction][0] + box[direction][1]) / 2
if val < mid {
box[direction][1] = mid
} else {
box[direction][0] = mid
code |= bits[bit]
}
bit++
if bit == 8 {
hash.WriteByte(code)
bit = 0
code = 0
hash[precision>>3] |= 1 << (7 - precision&7)
}
precision++
if precision == bitSize {
break
}
}
}
// precision%8 > 0
if code > 0 {
hash.WriteByte(code)
}
return hash.Bytes(), box

return hash, box
}

// Encode converts latitude and longitude to uint64 geohash code
Expand Down

0 comments on commit e5068f7

Please sign in to comment.