In some Aurelia binding code I needed to test whether a variable was a string or not. This is in a pretty hot code path so the algorithm needed to be as performant as possible. There seemed to be a handful of approaches out there so I dropped each one into a fiddle to determine whether they produced correct results:
Two methods worked in both the string literal ('hello'
) and new String('hello')
scenarios:
typeof s === 'string' || s instanceof String
Object.prototype.toString.call(s) === '[object String]'
I had a pretty good idea which would be fastest and jsperf confirmed: typeof || instanceof
wins by a landslide: