Disclaimer: This is micro-optimization. Performance is the enemy to every other quality. In some situations it needs to be prioritized, but most of the time, you should prioritize simplicity + readability.
If you really need to sanity check before inserting into WeakSet...
The specs for WeakSet say that only an Object
can be inserted into a WeakSet. So the question is really: "How do you check if a value is an Object
or not?".
Following the implementation for es6.weak-set.js
in the core-js library (which babel-polyfill uses), there's a transitive reference to _is-object.js
, which checks if a value is an object or not:
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
So, rest assured, your canBeAddedToWeakSet
is just about as good as it gets (although, I'd consider this ternary optimization and renaming it to isObject
).
Update: You may also want to consider the logical optimization mentioned in the comments (high-five @Patrick Roberts!).
When should you not sanity check before inserting into [any collection]?
If you have a strict real-time performance requirement, you may want to consider avoiding this check on every insert. If this is your case, here are your options:
1) Check on every insert
Pros: Protects the caller form handling the erroneous value
Cons: Performance cost of doing the check and branch prediction
2) Try / Catch
I would be concerned about setting up the overhead of exception handling with a function that needs high performance...
Pros: Protects the caller from handling the erroneous value
Cons: High performance cost of try/catch overhead (worse than if statement)
3) Let the caller handle the erroneous value
This tactic is about reducing the responsibility of the performance critical function. For some callers, this check may be totally unnecessary. For instance, in one domain, I may know for a fact that I will only ever have objects or nulls. In that case calling add(myWeakset, value || {})
is my best performance option.
Nevertheless, some domains may need the ability to addSafely
, so it might be beneficial to expose both methods...
Pros: Caller gets to maximize performance for their domain
Cons: Risk of irresponsible caller and increase in complexity