janet-lang / janet

A dynamic language and bytecode vm
https://janet-lang.org
MIT License
3.43k stars 221 forks source link

Add `buffer/from-bytes` #1259

Closed primo-ppcg closed 1 year ago

primo-ppcg commented 1 year ago

Filling a lexical gap, to avoid things like this:

(buffer (string/from-bytes ;data))
(buffer/push-byte @"" ;data)

or even this:

(def buf @"")
(each b data
  (buffer/push-byte buf b))

Adding this function has increased the size of the executable by 32 bytes on my system: master:

$ du -b `which janet`
801384  /usr/local/bin/janet

branch:

$ du -b `which janet`
801416  /usr/local/bin/janet

Of course, it's also faster than either alternative:

(use spork/test)

(var data (range 65 91))

(timeit-loop [:timeout 1]
  (buffer/from-bytes ;data))

(timeit-loop [:timeout 1]
  (buffer (string/from-bytes ;data)))

(timeit-loop [:timeout 1]
  (buffer/push-byte @"" ;data))
buffer/from-bytes 1.000s, 0.1529µs/body
string/from-bytes 1.000s, 0.2261µs/body
buffer/push-byte  1.000s, 0.2637µs/body
sogaiu commented 1 year ago

Here's what I got:

$ JANET_PATH=~/src/spork/jpm_tree/lib ~/src/janet.primo-ppcg/build/janet ~/scratch/buffer-from-bytes.janet 
Elapsed time: 1.000s, 0.2079µs/body
Elapsed time: 1.001s, 0.2947µs/body
Elapsed time: 1.000s, 0.3522µs/body