From 1e8a473ea60f8b898a0e71b1166754cb0e0e485e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartosz=20Dziewo=C5=84ski?= Date: Sun, 15 May 2016 00:30:56 +0200 Subject: [PATCH 1/3] Optimize encoding Symbols to JSON Previously, symbols would fall into the 'default' case and be stringified through rb_funcall(obj, intern_to_s, 0). That has the added overhead of function call and String object allocation. --- ext/yajl/yajl_ext.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ext/yajl/yajl_ext.c b/ext/yajl/yajl_ext.c index 25120100..075a1b32 100644 --- a/ext/yajl/yajl_ext.c +++ b/ext/yajl/yajl_ext.c @@ -209,6 +209,12 @@ void yajl_encode_part(void * wrapper, VALUE obj, VALUE io) { len = RSTRING_LEN(obj); CHECK_STATUS(yajl_gen_string(w->encoder, (const unsigned char *)cptr, len)); break; + case T_SYMBOL: + str = rb_id2str(SYM2ID(obj)); + cptr = RSTRING_PTR(str); + len = RSTRING_LEN(str); + CHECK_STATUS(yajl_gen_string(w->encoder, (const unsigned char *)cptr, len)); + break; default: if (rb_respond_to(obj, intern_to_json)) { str = rb_funcall(obj, intern_to_json, 0); From 9c7d3b0af677709bfb979130a918ea0668c446bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartosz=20Dziewo=C5=84ski?= Date: Sun, 15 May 2016 00:32:25 +0200 Subject: [PATCH 2/3] Optimize encoding String and Symbol keys to JSON rb_funcall has the added overhead of function call and, for Symbols, also String object allocation. String and Symbols keys are the common case here. --- ext/yajl/yajl_ext.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ext/yajl/yajl_ext.c b/ext/yajl/yajl_ext.c index 075a1b32..adcc9695 100644 --- a/ext/yajl/yajl_ext.c +++ b/ext/yajl/yajl_ext.c @@ -167,7 +167,12 @@ void yajl_encode_part(void * wrapper, VALUE obj, VALUE io) { keys = rb_funcall(obj, intern_keys, 0); for(idx=0; idx Date: Sun, 15 May 2016 00:41:48 +0200 Subject: [PATCH 3/3] Optimize encoding Fixnums to JSON A Fixnum can not be NaN, Infinity or -Infinity. Also, use rb_fix2str rather than rb_funcall(obj, intern_to_s, 0) to avoid function call overhead. --- ext/yajl/yajl_ext.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ext/yajl/yajl_ext.c b/ext/yajl/yajl_ext.c index adcc9695..edc3b8ab 100644 --- a/ext/yajl/yajl_ext.c +++ b/ext/yajl/yajl_ext.c @@ -199,6 +199,11 @@ void yajl_encode_part(void * wrapper, VALUE obj, VALUE io) { CHECK_STATUS(yajl_gen_bool(w->encoder, 0)); break; case T_FIXNUM: + str = rb_fix2str(obj, 10); + cptr = RSTRING_PTR(str); + len = RSTRING_LEN(str); + CHECK_STATUS(yajl_gen_number(w->encoder, cptr, len)); + break; case T_FLOAT: case T_BIGNUM: str = rb_funcall(obj, intern_to_s, 0);