400x通过将a.localeCompare(b)切换到(a <b≤-1:(a>b≤1:0))来加速分类 [英] 400x Sorting Speedup by Switching a.localeCompare(b) to (a&lt;b?-1:(a&gt;b?1:0))

查看:174
本文介绍了400x通过将a.localeCompare(b)切换到(a <b≤-1:(a>b≤1:0))来加速分类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过从

切换JavaScript排序函数

  myArray.sort(function(a,b){
return a.name.localeCompare(b.name);
});

  myArray.sort(function(a,b){
return(a.name< b.name?-1:(a.name> b.name?1:0));
});

我能够缩短在Chrome上从~1700毫秒到〜5毫秒。几乎是400倍的加速。不幸的是,这是以正确排序非英文字符串为代价的。



显然,当我尝试进行排序时,我无法在2秒内阻止UI。有什么我可以做,以避免可怕的慢localeCompare但仍然支持本地化的字符串?

解决方案

一种有效的方法,我处理/大多数/拉丁字符时发现的情况是在两个字符串匹配特定的正则表达式时使用操作符。 EG: / ^ [\w-.\s,] * $ /



这两个字符串都匹配表达式,最糟糕的情况是它比盲目地调用localeCompare要慢。



示例: http://jsperf.com/operator-vs-localecompage/11


By switching a javascript sort function from

myArray.sort(function (a, b) {
  return a.name.localeCompare(b.name);
});

to

myArray.sort(function (a, b) {
  return (a.name < b.name ? -1 : (a.name > b.name ? 1 : 0));
});

I was able to cut the time to sort a ~1700 element array in Chrome from 1993 milliseconds to 5 milliseconds. Almost a 400x speedup. Unfortunately this is at the expense of correctly sorting non-english strings.

Obviously I can't have my UI blocking for 2 seconds when I try to do a sort. Is there anything I can do to avoid the horribly slow localeCompare but still maintain support for localized strings?

解决方案

An effective Approach that I found when dealing with /mostly/ latin characters is to use the operator whenever both strings match a specific regex. EG: /^[\w-.\s,]*$/

It's much faster if both strings match the expression, and at worst it seems to be slightly slower than blindly calling localeCompare.

Example here: http://jsperf.com/operator-vs-localecompage/11

这篇关于400x通过将a.localeCompare(b)切换到(a <b≤-1:(a>b≤1:0))来加速分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆