bwmarrin / snowflake

A simple to use Go (golang) package to generate or parse Twitter snowflake IDs
BSD 2-Clause "Simplified" License
3.02k stars 374 forks source link

Add a method to encode the snowflake as a byte slice #4

Closed connor4312 closed 8 years ago

connor4312 commented 8 years ago

Previously there was a method called Bytes() []byte, but that simply returned the string representation as a byte slice. Not too efficient for storage and transport. This PR adds a method which returns a raw representation of the ID as an 8-bit byte array.

Also marshalling it into a byte array is ~10x faster than the JSON marshaller, since it looks like you folks like benchmarks 😉

BenchmarkMarshal-4      10000000           172 ns/op          32 B/op          1 allocs/op
BenchmarkIntMarshal-4   100000000           17.1 ns/op         0 B/op          0 allocs/op
bwmarrin commented 8 years ago

I like this one :) I'm just wondering what the best name for the function is. Can you give me a usage example of how you use this? I suspect you're using it somehow :)

It might even be reasonable to have this replace the old method, I'm not sure?

Maybe IntBytes makes sense in a way that isn't clicking in my head :) Which is very possible :)

connor4312 commented 8 years ago

Yea, I would have preferred to use Bytes(), but that was taken 😉

The idea is that this would be useful any time consumers need to store the snowflake ID in any kind of binary storage (such as BoltDB keys, perhaps), or transmit them over the network. It's more efficient to use an 8-byte array, which is easily sortable and monotonic (a boon for B+-tree based stores like BoltDB or MySQL) than to marshal the ID to a string then convert that to a 20-byte sequence.

I think it would be reasonable to replace the old method, but that is a breaking change, so it should be done with care...

connor4312 commented 8 years ago

Thanks! 😄

bwmarrin commented 8 years ago

You're welcome! Sorry I was slow.