简体   繁体   English

从数组中找到最小值和最大值的高性能和最佳方法

[英]performant and best way to find min and max from an array

I have a array there are some prices.我有一个数组有一些价格。 I want to get the min and max.我想得到最小值和最大值。 I have a way but I dont know if this way is bad an inefficent.我有办法,但我不知道这种方式是不是很糟糕。 Is there a better/performant way?有没有更好/性能更好的方法?

Array:大批:

sizes_and_colors: [
      {
        color: 'black',
        size: 'XS',
        amount: 3,
        price: 24.99
      },
      {
        color: 'black',
        size: 'S',
        amount: 4,
        price: 24.99
      },
      {
        color: 'blue',
        size: 'S',
        amount: 5,
        price: 24.95
      },
      {
        color: 'blue',
        size: 'XL',
        amount: 0,
        price: 24.95
      },
      {
        color: 'purple',
        size: null,
        amount: 4,
        price: 22.95
      },
      {
        color: 'beige',
        size: null,
        amount: 4,
        price: 20.99
      },
      {
        color: 'pink',
        size: 'S',
        amount: 2,
        price: 20.99
      },
      {
        color: 'green',
        size: null,
        amount: 4,
        price: 20.99
      },
      {
        color: 'silver',
        size: null,
        amount: 4,
        price: 20.99
      },
      {
        color: 'yellow',
        size: null,
        amount: 4,
        price: 20.99
      },

get lowest/highest pirce:获得最低/最高价格:

// get lowest price of the arr of sizes and colors
export const getLowestPrice = (sizes_and_colors: any) => {
  let arr: number[] = [];
   sizes_and_colors.map((el:any) => {
      if(el.price) {
        arr.push(el.price);
      }
   })
   return Math.min(...arr);
}

// get highest price of the arr of sizes and colors
export const getHighestPrice = (sizes_and_colors: any) => {
  let arr: number[] = [];
   sizes_and_colors.map((el:any) => {
      if(el.price) {
        arr.push(el.price);
      }
   })
   return Math.max(...arr);
}

I am very thankful for your answers and help.... ...........................................................................................非常感谢您的回答和帮助……………………………………………………………………………………………………………… ..................................................... ……

Just map to the price and take the max/min只需map的价格并取最大值/最小值

// get lowest price of the arr of sizes and colors
export const getLowestPrice = (sizes_and_colors: any) => {
   return Math.min(...sizes_and_colors.map((el) => el.price));
}

// get highest price of the arr of sizes and colors
export const getHighestPrice = (sizes_and_colors: any) => {
   return Math.max(...sizes_and_colors.map((el) => el.price));
}

Theory:理论:

Finding any specific element in an unsorted array is an O(n) operation, so a single loop over all array elements.在未排序的数组中查找任何特定元素是一个O(n)操作,因此对所有数组元素进行一次循环。 You currently seem to be doing one loop to extract the numeric components of an object, and then feeding them to Math.min() or Math.max() , which will have to do another loop.您目前似乎正在执行一个循环来提取 object 的数字分量,然后将它们提供给Math.min()Math.max() ,这将不得不执行另一个循环。 So you're doing O(2n) for one value, O(4n) for both.因此,您对一个值执行O(2n) ,对两个值执行O(4n)

If you know you're gonna need both, you can just keep two variables and check for both min and max in every loop iteration.如果您知道两者都需要,您可以只保留两个变量并在每次循环迭代中检查最小值和最大值。

let min = Infinity, max = -Infinity;
for(let i = 0; i < arr.length; ++i)
{
    let p = arr[i].price;
    if(p < min) min = p;
    if(p > max) max = p;
}

Certainly not idiomatic JavaScript, but this way you get both values in O(n) .当然不是惯用的 JavaScript,但这样你就可以在O(n)中获得两个值。

Practice:实践:

Run tests.运行测试。 JavaScript engines apply all sorts of crazy optimisations, and it may very well be possible that builtins like Array.map() and Math.min() / Math.max() enjoy better optimisation than a hand-rolles JavaScript loop. JavaScript 引擎应用了各种疯狂的优化,并且很有可能像Array.map()Math.min() / Math.max()这样的内置函数比手卷 JavaScript 循环具有更好的优化。

Also, beware of diminishing returns.另外,请注意收益递减。 If you expect the array to not contain at least a thousand elements, then worrying about performance on searching it is almost certainly a waste of time, and going with Samathingamajig's answer is likely preferrable for readability.如果您希望数组不包含至少一千个元素,那么担心搜索它的性能几乎可以肯定是浪费时间,并且为了可读性而选择 Samathingamajig 的答案可能更可取。

But if performance truly is critical in your case, benchmark a raw loop against the other solutions.但是,如果在您的情况下性能确实很关键,请将原始循环与其他解决方案进行基准测试。 Do a couple million iterations, run them across different browsers, etc.做几百万次迭代,在不同的浏览器上运行它们,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM