DEV Community

loading...

Discussion on: Code Snippet Series: Remove Junk from Array

Collapse
functional_js profile image
Functional Javascript Author • Edited

Good catch BeasTea,

I've replicated your findings.
It's impressively about 4 TIMES faster.

Interestingly, if you compare the v.constructor and v typeof independently, performance-wise they are effectively the same.

The reason I've preferred v.constructor over typeof is because of its robustness factor; the v typeof returns false for explicit instantiations of types, eg. "new String()"

So what's happening here is a compiler optimization for typeof; where the compiler fails to optimize for the v.constructor.

This would actually be a bug, or at least an optimization deficiency, in the V8 compiler.

Because of the vagaries of compilers, we must perf-test our code and hunt out performance bottlenecks.

//@perftest

//a. typeof
const isEmptyStr = s => typeof s === "string" && s.trim() === "";
timeInLoop("isEmptyStr", 100e6, () => isEmptyStr("asdf"))
//isEmptyStr: 1e+8: 1.019s

//b. s.constructor
const isEmptyStr2 = s => s !== null && s !== undefined && s.constructor === String && s.trim() === "";
timeInLoop("isEmptyStr2", 100e6, () => isEmptyStr2("asdf"))
////isEmptyStr2: 1e+8: 1.038s
Collapse
beastea3 profile image
BeasTea

Thx for ur explanation, that's impressive!!!

Forem Open with the Forem app