当运行for循环时,哪个在coffeescript中更好/更有效

Which is better/more efficient in coffeescript when running a for loop?

本文关键字:coffeescript 更好 有效 for 运行 循环      更新时间:2023-09-26

在javascript中有两种功能相等的方法来编写以下函数,哪一种更好或更有效,为什么?

(str) ->
  s = 0
  for i in [0...str.length]
    s += str.charCodeAt i 
  s

(str) ->
  s = 0
  for i in str
    s += i.charCodeAt 0 
  s

旁白:你能建议其他的方法吗?

编辑:根据JSPerf,第一个更快:http://jsperf.com/coffee-for-loop-speed-test -这是为什么?

第一种方法更优雅也更高效。第二步在将字符串转换为charCode之前,将字符串的每个字符不必要地复制到一个单独的字符串。

你熟悉函数式编程吗?Coffeescript + Underscore.js一起工作非常棒。您可以使用ECMAScript 5上定义的本地Array#reduce,也可以使用下划线函数。第一个示例:

(s.charCodeAt(0) for s in "hello").reduce((acc, x) -> acc + x) # 532