Here's Google's implementation of String.startsWith()
taken from Closure Library:
goog.string.startsWith = function(str, prefix) {
return str.lastIndexOf(prefix, 0) == 0;
};
I was wondering why did they choose lastIndexOf
over indexOf
given the fact that:
indexOf
is twice as fast in some cases.- Browser compatibility is the same.
It's not about micro-optimization, I really do believe that:
return str.indexOf(prefix) == 0;
is simpler, cleaner and happened to be faster than:
return str.lastIndexOf(prefix, 0) == 0;
How is lastIndexOf
better in this case?