Skip to content

Commit

Permalink
fix: jv_number_value should cache the double value of literal numbers
Browse files Browse the repository at this point in the history
The code of `jv_number_value` is intended to cache the double value of
literal numbers, but it does not work because the function accepts the
`jv` struct by value. This patch fixes the behavior by checking if the
double value is `NaN`, which is the initial value. This patch apparently
does not cache the value if the literal is `NaN`, but improves the
performance of major use cases; e.g. `range(1000000)` runs 25% faster.
  • Loading branch information
itchyny committed Feb 2, 2025
1 parent d0adcbf commit 546e774
Showing 1 changed file with 3 additions and 7 deletions.
10 changes: 3 additions & 7 deletions src/jv.c
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,6 @@ enum {
JVP_NUMBER_DECIMAL = 1
};

#define JV_NUMBER_SIZE_INIT (0)
#define JV_NUMBER_SIZE_CONVERTED (1)

#define JVP_FLAGS_NUMBER_NATIVE JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_NATIVE, 0))
#define JVP_FLAGS_NUMBER_LITERAL JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_DECIMAL, 1))

Expand Down Expand Up @@ -590,7 +587,7 @@ static jv jvp_literal_number_new(const char * literal) {
return JV_INVALID;
}

jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, JV_NUMBER_SIZE_INIT, {&n->refcnt}};
jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&n->refcnt}};
return r;
}

Expand Down Expand Up @@ -698,9 +695,8 @@ double jv_number_value(jv j) {
if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL)) {
jvp_literal_number* n = jvp_literal_number_ptr(j);

if (j.size != JV_NUMBER_SIZE_CONVERTED) {
if (isnan(n->num_double)) {
n->num_double = jvp_literal_number_to_double(j);
j.size = JV_NUMBER_SIZE_CONVERTED;
}

return n->num_double;
Expand Down Expand Up @@ -731,7 +727,7 @@ int jvp_number_is_nan(jv n) {
return decNumberIsNaN(pdec);
}
#endif
return n.u.number != n.u.number;
return isnan(n.u.number);
}

int jvp_number_cmp(jv a, jv b) {
Expand Down

0 comments on commit 546e774

Please sign in to comment.