質問

In my Node.js app I have a database layer that calls toString on input parameters that need to be passed to the database as a string (for example, numbers). The places where I pass parameters to the library, should I call toString there too? On the one hand, I like being explicit. On the other, I'm calling toString on something that is already a string. If that is unnecessary, I'd rather save the CPU cycles.

How costly is it to call toString on a string?

役に立ちましたか?

解決

How costly is it to call toString on a string?

In any decent engine (and V8 is a decent engine), it should be nearly free. But it still has to do the property lookup through the prototype chain, to make sure someone hasn't overridden it. So it won't be free, just cheap.

...should I call toString there too?

This one's subjective. I'm with @dystroy: There's no need. Further, it's probably best to give the API as much information to work with as possible, in case they enhance it in future releases. Unless the API requires that you give it strings, I'd preserve information by not converting to string before handing params over.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top