如何快速匹配两个数组中的数据?AutoIt代码优化需求
高效匹配IMDB记录数组的优化方案
问题背景
现有两个数组:
- $r01:包含8000行数据,为单列IMDB ID列表(无'tt'前缀)
- $info01:包含44000行数据,每行是带IMDB ID(带'tt'前缀)的完整影片详情
需求是找出$r01中存在于$info01的所有记录,原采用双层For循环实现(代码如下),但在i7 7700k、16GB内存设备上耗时长达数小时,急需更高效的解决方案。
原低效代码
For $i = 0 to UBound($r01)-1 ; first array For $j = 0 to UBound($info01)-1 ; second array if StringInStr($info01[$j], 'tt' & $r01[$i])>0 Then ; search ID - I will add 'tt' to original array, to shave off a few seconds of processing _ArrayAdd($found, $all[$j] & @TAB & $r01[$i]) ; add match to $found array exitloop ; exit loop, I do not need duplicate results (yes, they are possible) endif Next Next
优化思路
原方案时间复杂度为O(n*m)(8000*44000=3.52亿次循环),效率极低。改用哈希表(关联数组)实现快速查找,将时间复杂度降至O(n+m),大幅提升速度:
- 先把$r01的所有IMDB ID加上'tt'前缀,存入关联数组作为键(值仅用于标记存在)
- 遍历$info01的每条记录,检查是否包含关联数组中的键
- 匹配成功则将记录加入结果数组
优化后代码
; 1. 构建IMDB ID的哈希表(关联数组) Local $idHash = {} For $i = 0 To UBound($r01)-1 $idHash['tt' & $r01[$i]] = 1 ; 用带tt前缀的ID作为键 Next ; 2. 遍历info数组快速匹配 Local $found = [] For $j = 0 To UBound($info01)-1 Local $currentLine = $info01[$j] ; 遍历哈希表的键,检查当前行是否包含该ID For $id In $idHash If StringInStr($currentLine, $id) > 0 Then ; 注意:原代码中的$all[$j]疑似笔误,改为$info01[$j] _ArrayAdd($found, $info01[$j] & @TAB & StringTrimLeft($id, 2)) ; 移除已匹配的ID,避免重复匹配(不需要去重可跳过) $idHash[$id] = Null ExitLoop EndIf Next Next
进一步优化建议
如果能从$info01的每条记录中直接提取IMDB ID(比如通过正则匹配),效率会更高,避免在整行文本中做字符串查找:
; 用正则提取行中的IMDB ID(格式为tt+数字) Local $regex = ObjCreate("VBScript.RegExp") $regex.Pattern = "tt\d+" $regex.Global = False ; 构建哈希表步骤同上... ; 遍历info数组时直接提取ID匹配 For $j = 0 To UBound($info01)-1 Local $match = $regex.Execute($info01[$j]) If $match.Count > 0 Then Local $extractedId = $match(0).Value If $idHash[$extractedId] Then _ArrayAdd($found, $info01[$j] & @TAB & StringTrimLeft($extractedId, 2)) $idHash[$extractedId] = Null EndIf EndIf Next
内容的提问来源于stack exchange,提问作者Paul Queen Soft
相关产品推荐
相关产品推荐

