array vs string accumulators for obj2qs (v2)

Revision 2 of this benchmark created on


Setup

const p = {
  single1: "one",
  many2: ["two", "th?e e"],
  many0: [],
  single0: "",
  many3: ["a", "b", "c"],
  "w t f": ["ikr", "lol"],
  num: 1.23,
  zero: 0,
  bool1t: true,
  bool1f: false,
  bool2: [true, false]
};

const obj2qs_arr = (obj) => {
  return Object.entries(obj).reduce((rv, [key, val]) => {
    if (val.length > 0 || ["number", "boolean"].indexOf(typeof val) !== -1) {
      rv.push((Array.isArray(val) ? val : [val]).map(
        v => `${encodeURIComponent(key)}=${encodeURIComponent(v)}`
      ).join("&"))
    }
    return rv;
  }, []).join("&")
};

const obj2qs_str = (obj) => {
	return Object.entries(obj).reduce((rv,[key,val])=>{
    if(val.length > 0 || ["number","boolean"].indexOf(typeof val) !== -1 ){
      rv += (rv.length > 0 ? "&" : "")
     		+ (Array.isArray(val) ? val : [val]).map(
        	v=>`${encodeURIComponent(key)}=${encodeURIComponent(v)}`
        ).join("&");
  	}
    return rv;
  },"")
};

Test runner

Ready to run.

Testing in
TestOps/sec
array
obj2qs_arr(p) 
ready
str
obj2qs_str(p) 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.