There are two functionally equivalent ways of writing the following function in javascript, which is better or more efficient, and why?
(str) ->
s = 0
for i in [0...str.length]
s += str.charCodeAt i
s
or
(str) ->
s = 0
for i in str
s += i.charCodeAt 0
s
Aside: Can you suggest any other methods of doing this?
Edit: According to JSPerf, the first is faster: http://jsperf.com/coffee-for-loop-speed-test – why is this?
The first is both more elegant and more efficient. The second copies each character of the string to a separate string unnecessarily, before converting it to a
charCode.