【问题标题】:(JavaScript) Creating a more efficient algorithm than the one I had(JavaScript) 创建一种比我现有的更有效的算法
【发布时间】:2019-12-07 03:24:01
【问题描述】:

我有这种情况:

    let scans = [
      { source: "10.0.0.2", destination: "20.0.0.2" }
      { source: "10.0.0.4", destination: "20.0.0.6" }
    ]

    const handleScan = (source, destination, port) => {
      let newScan = {
        source : source, 
        destination : destination
      }

      for (scan of scans) {
        if (scan.source !== source && scan.destination !== destination)
        scans.push(newScan)
      }
    }

现在,这个函数每秒执行 1000 次,这意味着每次都使用 for 循环来查看该对是否存在是非常糟糕的。 你会建议我如何提高效率?

【问题讨论】:

  • 如果您的代码没有问题并且它确实可以工作,但您只是想查看它并可能改进它,我认为您可以在codereview.meta.stackexchange.com 上找到更好的答案
  • 您真的是要推送源和目标与任何现有扫描不同的扫描吗?
  • 您可以创建一个Set,它是由|分隔的源和目标的组合
  • 这会将newScan 的大量副本推送到您的阵列上,这可能是您的性能问题的来源。如果您调用handleScan 一次,并使用以前未见过的IP 作为源和目标,则通过为已在扫描中的每个元素调用一次scans.push(newScan) 将扫描大小加倍。如果您使用新 IP 每秒调用 1000 次,scans 将很快占用比整个宇宙更多的内存
  • 就像@Paulpro 所说,您当前的算法似乎甚至无法正常工作。该功能应该解决的actual problem 是什么?这个scans 数组在其他地方是如何使用的?

标签: javascript algorithm processing-efficiency


【解决方案1】:

目标是跟踪所有来源的所有目的地吗?如果是这样,那不是它目前正在做的事情。这样做的方法如下:

let scans = [
  { source: "10.0.0.2", destination: "20.0.0.2" }
  { source: "10.0.0.4", destination: "20.0.0.6" }
]

const handleScan = (source, destination, port) => {
  let newScan = {
    source : source, 
    destination : destination
  }

  var scanFound = false;
  for (scan of scans) {
    if (scan.source !== source && scan.destination !== destination){
      scanFound = true;
      break;
    }
  }
  if(!scanFound){
    scans.push(newScan)
  }
}

如果这是目标,我建议将格式更改为以源为键、目标为值的对象,这样它是查找而不是循环:

var destinationsBySource = {
  "10.0.0.2": ["20.0.0.2"],
  "10.0.0.4": ["20.0.0.6"]
]

var handleScan = function(source, destination){
  //Initialize destinations as an array if source is not there
  destinationsBySource[source] = destinationsBySource[source] || [];

  //Add the destination if needed
  if(destinationsBySource[source].indexOf(destination) == -1){
    destinationsBySource[source].push(destination);
  }
};//End of handleScan function

【讨论】:

  • 非常感谢。这是我记得在这种情况下应该采用的解决方案类型,但不能完全做到。
  • @YossiDagan 欢迎,很高兴我能帮上忙 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多