By switching a javascript sort function from

通过切换javascript排序函数。

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.

从1993毫秒到5毫秒,我可以节省时间来对Chrome中的1700元素数组进行排序。几乎400倍加速。不幸的是,这是以正确排序非英语字符串为代价的。

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?

很明显,当我尝试做排序时,我不能让UI阻塞2秒。我可以做些什么来避免非常缓慢的localeCompare,但仍然保持对本地化字符串的支持?

4 个解决方案

#1


9

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,]*$/

我在处理/主要/拉丁字符时发现的一种有效方法是,每当两个字符串匹配特定的正则表达式时,都使用操作符。如:/ ^[\ 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.

如果两个字符串都匹配这个表达式,那么它的速度要快得多,在最坏的情况下,它似乎要比盲目地调用localeCompare稍微慢一些。

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

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

更多相关文章

  1. JS计算任意字符串宽度
  2. JavaScript中两个感叹号的作用
  3. 使用jackson json将属性添加到json字符串
  4. ajax请求返回一个空字符串作为响应
  5. 在Javascript中将带有空格的字符串数组转换为小写,然后在Webkit中
  6. javascript添加两个文本框值,并在asp.net中显示为第三
  7. 如何将带有双引号反斜杠的JSON字符串转换为Javascript对象
  8. Javascript正则表达式应该允许空和非空字符串,但它不会
  9. 两个svg文件用javascript合并的问题?

随机推荐

  1. android多线程访问服务器数据
  2. android之layout_weight使用
  3. activity的xml详解
  4. Android Webview 和Javascript交互,实现An
  5. Android插件配置-Android Extension介绍
  6. android 重力感应初步认识
  7. Android调用输入法软键盘,返回输入的内容
  8. android中使用afinal一行代码显示网络图
  9. Android文件系统保护——dmverity
  10. Camera Flash的获得权限