Closed jdalton closed 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.
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.
(+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
\cc @bmeurer for more insights into the perf characteristics here.
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.
Thank you @bmeurer!
I noticed json-6 uses
new Number
in places creating number objects then immediately coerces it to a number primitive. Instead you can use justNumber(...)
without thenew
or+value
.