Skip to content

Commit 5b4b24e

Browse files
authored
Merge pull request #656 from byroot/opt-fbuffer_append_long
Optimize `fbuffer_append_long`
2 parents 844a663 + 0655b58 commit 5b4b24e

File tree

2 files changed

+10
-17
lines changed

2 files changed

+10
-17
lines changed

benchmark/encoder.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ def benchmark_encoding(benchmark_name, ruby_obj, check_expected: true, except: [
6464
benchmark_encoding "small hash", { "username" => "jhawthorn", "id" => 123, "event" => "wrote json serializer" }
6565

6666
# On these benchmarks we perform well. Either on par or very closely faster/slower
67+
benchmark_encoding "integers", (1_000_000..1_001_000).to_a, except: %i(json_state)
6768
benchmark_encoding "mixed utf8", ([("a" * 5000) + "€" + ("a" * 5000)] * 500), except: %i(json_state)
6869
benchmark_encoding "mostly utf8", ([("€" * 3333)] * 500), except: %i(json_state)
6970
benchmark_encoding "twitter.json", JSON.load_file("#{__dir__}/data/twitter.json"), except: %i(json_state)

ext/json/ext/fbuffer/fbuffer.h

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -107,33 +107,25 @@ static void fbuffer_append_char(FBuffer *fb, char newchr)
107107
}
108108

109109
#ifdef JSON_GENERATOR
110-
static void freverse(char *start, char *end)
111-
{
112-
char c;
113-
114-
while (end > start) {
115-
c = *end, *end-- = *start, *start++ = c;
116-
}
117-
}
118-
119110
static long fltoa(long number, char *buf)
120111
{
121-
static char digits[] = "0123456789";
112+
static const char digits[] = "0123456789";
122113
long sign = number;
123114
char* tmp = buf;
124115

125116
if (sign < 0) number = -number;
126-
do *tmp++ = digits[number % 10]; while (number /= 10);
127-
if (sign < 0) *tmp++ = '-';
128-
freverse(buf, tmp - 1);
129-
return tmp - buf;
117+
do *tmp-- = digits[number % 10]; while (number /= 10);
118+
if (sign < 0) *tmp-- = '-';
119+
return buf - tmp;
130120
}
131121

122+
#define LONG_BUFFER_SIZE 20
132123
static void fbuffer_append_long(FBuffer *fb, long number)
133124
{
134-
char buf[20];
135-
unsigned long len = fltoa(number, buf);
136-
fbuffer_append(fb, buf, len);
125+
char buf[LONG_BUFFER_SIZE];
126+
char *buffer_end = buf + LONG_BUFFER_SIZE;
127+
long len = fltoa(number, buffer_end - 1);
128+
fbuffer_append(fb, buffer_end - len, len);
137129
}
138130

139131
static VALUE fbuffer_to_s(FBuffer *fb)

0 commit comments

Comments
 (0)