简体   繁体   English

性能慢的自定义脚本 GAS

[英]Slow Performance Custom Script GAS

So, I've written (for lack of answers + improving my skills) a search script that would do basically what.indexOf does.所以,我写了(因为缺乏答案+提高我的技能)一个搜索脚本,它基本上可以做 .indexOf 所做的事情。

function search(ref, data) {

  var x
  var y
  var result = []

  if (data == '' || data == null) {
  } else {
    for (x = 0; x < data.length; x++) {
      if (data[x] == ref[0]) {                //achando match inicial
        var proto = [];
        for (y = 0; y < ref.length; y++) {
          if (data[x+y] == ref[y]) {          //gravando tentativas de match completo
          proto.push(data[x+y])
          }
        }
        var proto2 = proto.join('')
        if (proto2 == ref) {                   //testando match completo
            result.push(x)
        }
      }
    }
  }
  if (result == '' || result == null) {
  } else {
    return result[0]
  }
}

It works fine within other little codes and custom functions that do not require too much looping, but when I wrote a more robust script I found that my code is roughly 3000x slower than the native.indeOf.它在其他不需要太多循环的小代码和自定义函数中运行良好,但是当我编写更强大的脚本时,我发现我的代码比 native.indeOf 慢大约 3000 倍。

Why would I incur in such a difference?为什么我会产生这样的差异?

Issue:问题:

Your function is comparing each character from ref separately with a data character, in an inner loop, pushing each character match inside an array ( proto ) and using join to transform the array back to a string ( proto2 ), before comparing it to the original ref .您的 function 在内部循环中将ref中的每个字符分别与data字符进行比较,将每个字符匹配推入数组( proto )并使用join将数组转换回字符串( proto2 ),然后再将其与原始字符进行比较ref

This is extremely inefficient and could be greatly simplified, so no question this function is much slower than String.prototype.indexOf() .这是非常低效的并且可以大大简化,所以毫无疑问这个 function 比String.prototype.indexOf()慢得多。

Solution:解决方案:

You could have a single loop instead, iterating through data , and for each iteration, retrieve a slice of data with the same length as ref , before comparing this slice with ref .您可以改为使用单个循环,遍历data ,并且对于每次迭代,检索与ref长度相同的data 切片,然后将此切片与ref进行比较。 If both values match, the string ref has been found in data , and the corresponding index is returned:如果两个值都匹配,则在data中找到了字符串ref ,并返回相应的索引:

function searchString(ref, data) {
  for (let i = 0; i <= data.length - ref.length; i++) {
    if (ref === data.slice(i, i + ref.length)) return i;
  }
  return -1;
}

While using this function, I get similar execution times than with indexOf .在使用这个 function 时,我得到的执行时间与indexOf相似。

Reference:参考:

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

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