cryptocoinjs / base-x

Encode/decode any base
MIT License
312 stars 75 forks source link

Performance improvement #74

Closed oscxc closed 1 year ago

oscxc commented 3 years ago

Just change (source[psz]) to (psz < source.length) in line 82.

junderw commented 3 years ago

can you show any benchmarks?

oscxc commented 3 years ago

can you show any benchmarks?

`const rand = (a, b) => { return Math.floor(Math.random() * (b - a + 1) + a); }; let BaseX = require('./basex')('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');

let buffer = Buffer.alloc(16); for(let i = 0; i < 16; i++){ buffer[i] = rand(0, 255); } let str = BaseX.encode(buffer); let buffer2 = BaseX.decode(str); console.log(buffer.equals(buffer2)); //true

let t1 = new Date().getTime(); for (let i = 0; i < 1000000; i++){ let test = BaseX.decode(str); } let t2 = new Date().getTime(); console.log(t2 - t1);

//cpu i9-9900kf

//use present (source[psz]) //593ms, 554ms, 596ms, 607ms, 605ms, 597ms, 627ms, 627ms, 596ms, 622ms

//change to (psz < source.length) //546ms, 539ms, 563ms, 541ms, 566ms, 546ms, 569ms, 543ms, 539ms, 537ms

`

steveluscher commented 1 year ago

This makes a ton of sense to me. source is asserted to be a string, psz is monotonically increasing, and psz >= source.length is a good indication that you've run out of characters.

Any objection to merging this?

steveluscher commented 1 year ago

The effect on decode seems quite significant. Using this repo's benchmark suite:

Before:

~/src/base-x/benchmark$ (cd ../ && npm run build) && SEED=8854dc2a353e143702ef1b29874b63a4 npm start

> base-x@4.0.0 build
> tsc -p ./tsconfig.json ; standard --fix

> base-x-benchmark@0.0.0 start
> node index.js

Seed: 8854dc2a353e143702ef1b29874b63a4
--------------------------------------------------
encode x 389,085 ops/sec ±0.34% (9 runs sampled)
decode x 427,013 ops/sec ±0.31% (8 runs sampled)
==================================================

After:

~/src/base-x/benchmark$ (cd ../ && npm run build) && SEED=8854dc2a353e143702ef1b29874b63a4 npm start

> base-x@4.0.0 build
> tsc -p ./tsconfig.json ; standard --fix

> base-x-benchmark@0.0.0 start
> node index.js

Seed: 8854dc2a353e143702ef1b29874b63a4
--------------------------------------------------
encode x 389,681 ops/sec ±0.32% (8 runs sampled)
decode x 448,309 ops/sec ±0.09% (9 runs sampled)
==================================================
steveluscher commented 1 year ago

Feel like slamming this in, @junderw? This should make tons of downstream deps faster!

junderw commented 1 year ago

Travis CI is broken, needs to be moved to Github CI.