d3x0r / JSON6

JSON for Humans (ES6)
Other
236 stars 14 forks source link

new Number use can be simplified #6

Closed jdalton closed 6 years ago

jdalton commented 6 years ago

I noticed json-6 uses new Number in places creating number objects then immediately coerces it to a number primitive. Instead you can use just Number(...) without the new or +value.

d3x0r commented 6 years ago

Yes; Number() over new Number() is an (10x) optimization... but it's not + value it's * value to recover the sign which ends up outside the number because of keyword -Infinity.

Number( val.string ) * (val.negative?-1:1) is slightly faster than val.negative?-Number( val.string ):Number(val.string); (2757ms:3811ms)

(val.negative?-1:1) * Number(val.string); is slower (3308ms)

github tests/testNumberConvert.js

published 0.1.121 Oops; that should just be negative not val.negative. (fixing) Simple number object was also bad... publish 0.1.122 added tests/json6NumberTest.js ; minor differences between negative pre or post mulitply disappeared... negative?-Number():Number() is slightly slower still.

jdalton commented 6 years ago

Ah cool. +value is just a lighter weight form of Number(). For your use you might need to wrap it in the appropriate parens. Number() performs the same internal ToNumber operation as unary plus.

d3x0r commented 6 years ago

(+val.number) is 50% slower....

(+val.number)
took: 5040
took: 5238
took: 4272
took: 4753
took: 4479
took: 4616

// Number( val.number)
took: 3820
took: 3589
took: 2780
took: 3322
took: 3146
took: 3056
jdalton commented 6 years ago

\cc @bmeurer for more insights into the perf characteristics here.

bmeurer commented 6 years ago

Traditionally +x was desugared to 1*x (which no longer works with BigInts though), so that's why depending on what you do exactly, +x can be a bit slower than just invoking the Number constructor.

jdalton commented 6 years ago

Thank you @bmeurer!