我遇到了字符串距离函数运行过慢的问题。我已经缩小了范围,下面是比较耗时的部分(时间是10K个字符串比较的时间):
// desired behavior - 400ms
dp[c + 257] = Math.min(dp[c + 256] + 1, dp[c + 1] + 1, dp[c] + (a[i] != b[j]));
// this is somewhat faster - 300ms
dp[c + 257] = Math.min(dp[c + 256] + 1, dp[c + 1] + 1);
dp[c + 257] = Math.min(dp[c + 257], dp[c] + (a[i] != b[j]));
// even faster - 50ms
dp[c + 257] = Math.min(dp[c + 256] + 1, dp[c + 1] + 1);
dp[c + 257] = Math.min(dp[c + 257], dp[c] + (a[i] != b[j] ? 1 : 0));
首先,将
Math.min
拆分成两个调用比一次使用三个参数更快 - 这是如何可能的?其次,为什么添加一个显式的三元表达式比依赖于从布尔值到整数的隐式转换要快得多?这里有一个小示例:https://jsfiddle.net/6bnLvbt6/
a[i]!=b[j]?1:0
也基本上是类型转换,只不过它在JS中是显式完成的,肯定比本地的更昂贵? - rivMath.min
的二元版本与具有任意参数的Math.min
完全不同的代码路径。 - apsillersMath.min
实际上是在 JS 中实现的,而不是原生代码中吗? - riv