Skip to content
Myr

fix: `jv_number_value` should cache the double value of literal numbers (#3245)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The code of `jv_number_value` is intended to cache the double value of literal numbers, but it does not work because it accepts the `jv` struct by value. This patch fixes the behavior by checking if the double value is `NaN`, which indicates the unconverted value. This patch improves the performance of major use cases; e.g. `range(1000000)` runs 25% faster.

authored by itchyny · committed by GitHub · parent 64bd8ba · Browse files · 1 file+7 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+7 added−7 removed

  • other:+7 added−7 removed

1 file+7 added−7 removed

modified:src/jv.c+7 added-7 removed
204 unmodified lines
205 JVP_NUMBER_NATIVE = 0,206 JVP_NUMBER_DECIMAL = 1207};208209#define JV_NUMBER_SIZE_INIT (0)210#define JV_NUMBER_SIZE_CONVERTED (1)211209#define JVP_FLAGS_NUMBER_NATIVE JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_NATIVE, 0))210#define JVP_FLAGS_NUMBER_LITERAL JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_DECIMAL, 1))211212// the decimal precision of binary double
370 unmodified lines
583 if (ctx->status & DEC_Conversion_syntax) {584 jv_mem_free(n);585 return JV_INVALID;586 }587 if (decNumberIsNaN(&n->num_decimal)) {588 jv_mem_free(n);589 return jv_number(NAN);590 }591591 jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, JV_NUMBER_SIZE_INIT, {&n->refcnt}};592 jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&n->refcnt}};593 return r;594}595596static double jvp_literal_number_to_double(jv j) {
99 unmodified lines
696#ifdef USE_DECNUM697 if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL)) {698 jvp_literal_number* n = jvp_literal_number_ptr(j);699699 if (j.size != JV_NUMBER_SIZE_CONVERTED) {700 if (isnan(n->num_double)) {701 n->num_double = jvp_literal_number_to_double(j);701 j.size = JV_NUMBER_SIZE_CONVERTED;702 }703704 return n->num_double;705 }
22 unmodified lines
728 decNumber *pdec = jvp_dec_number_ptr(n);729 return decNumberIsNaN(pdec);730 }731#endif732 return n.u.number != n.u.number;732 return isnan(n.u.number);733}734735jv jv_number_negate(jv n) {736 assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));
1260 unmodified lines