我知道类似这样的问题在这里,但是我要特别关注处理速度。我正在做的事情已经有效。
我有一个包含标题进行排序的数组。有些标题以双引号开头,例如,"You're in Charge" Leadership in Difficult Times
而某些标题以A,An或The开头,例如A Collective Impact on Literacy
。我想在排序时忽略它们,这很好用:
theArray.sort(function(a, b) {
var titleA = a.title.toLowerCase();
titleA = removeCertainLeadingCharacters(titleA);
var titleB = b.title.toLowerCase();
titleB = removeCertainLeadingCharacters(titleB);
return (titleA < titleB) ? -1 : (titleA > titleB) ? 1 : 0;
});
函数removeCertainLeadingCharacters()的定义方式如下:
function removeCertainLeadingCharacters(title) {
// remove leading quote from a lowercase title, and also leading articles (a, the, an)
if (title.indexOf('"') == 0) title = title.substr(1);
words = title.split(" ");
if(words[0] == 'a' || words[0] == 'the' || words[0] == 'an' ) {
return words.splice(1).join(" ");
}
else {
return title;
}
}
我唯一的问题是是否有更快的方法。如果我要对大约800个标题的数组进行排序,而忽略了对removeCertainLeadingCharacter()的调用,则排序速度将非常快。如果我添加函数调用,则速度会变慢。速度并没有太大的阻力,但是速度明显慢一些。没有呼叫,它基本上是瞬时的。
所以我只是想知道完成这项任务的速度是否比我正在做的更快。
谢谢。
这可以为您节省一些时间(50%的时间),因为只检查语句中的第一个单词就不需要拆分。
function removeCertainLeadingCharacters(title) {
// remove leading quote from a lowercase title, and also leading articles (a, the, an)
if (title.indexOf('"') === 0) {
title = title.substr(1);
}
if (title.startsWith('a ')) {
title = title.substring(2);
} else if (title.startsWith('an ')) {
title = title.substring(3);
} else if (title.startsWith('the ')) {
title = title.substring(4);
}
return title;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句