这是我的源代码:
// start at zero
var count = 0;
// loop through the items
for(var i = 0; i < hours.length; i++) {
// 1. check to see if the current item has a key called "description"
// 2. check to see if the current item's "description" key isn't empty
// NOTE: white-space only values aren't valid
if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
// increment the count (by one)
count += 1;
}
}
// return the count
return count;删除注释时,代码如下所示:
var count = 0;
for(var i = 0; i < hours.length; i++) {
if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
count += 1;
}
}
return count;这似乎相当昂贵(特别是对于较大的数组)。是否有更好(最好是更简洁)的方法来计算数组中包含没有空值的特定键的对象的数量?
信息:我不能使用jQuery或LoDash/下划线,所有方法都必须在浏览器中本地可用,并且具有良好的浏览器支持(IE8+)。
发布于 2019-02-25 00:34:32
使用String.replace意味着您需要跨出您正在测试的每个字符串中的每个字符。不仅如此,它还需要分配内存来保存产生的新字符串。
如果您测试一个非空白字符,它会快得多。这样,它只需要测试第一个非空白,它不需要额外的内存。
而且,Object.hasOwnProperty速度慢,因为它必须沿着prototype链向上工作才能得到答案,并且只有当您认为正在测试的对象具有包含正在测试的属性名称的原型链时,才应该使用它。
最后一点。这不是您提供的代码的一部分,但是为了提高性能,属性hour.description不应该只包含空格。设置该属性时,检查它(如hour.description = descriptionString.trim(); )
因此,如果您有未经过检查的描述字符串
var i, count = 0;
for (i = 0; i < hours.length; i++) {
count += hours[i].description && (/\S/).test(hours[i].description) ? 1 : 0;
}
return count;或
如果已经对描述进行了审查,那么下面的说明将是最快的
var i, count = 0;
for (i = 0; i < hours.length; i++) {
count += hours[i].description ? 1 : 0;
}
return count;发布于 2019-02-24 15:37:09
我不是JS性能专家,但您可以尝试如下:
var count = 0;
const numHours = hours.length; // Don't denominate the length on each loop.
for(var i = 0; i < numHours; i++) {
let description = hours[i].description; // Don't denominate the description two times.
// Just search for something that isn't a space character (yes, capital "S").
if(description && (description.search(/\S/g) !== -1)) {
count++; // May be better too.
}
}
return count;而且,RegEx通常是昂贵的,你可以试着摆脱它们。
https://codereview.stackexchange.com/questions/214166
复制相似问题