如何提高迭代循环性能

如何解决如何提高迭代循环性能

所以我试图遍历一组数据并基本上创建一个结果树,显示所有不同的路径,我终于成功了,但它运行得非常慢,从我的测试来看,这是因为重复搜索功能和最后的附加正则表达式匹配,因为该功能无法确定最终结果是否与标准窗口匹配。如何检查根调用以过滤以 windows: 开头的结果,以及如何删除重复搜索功能。我的猜测是我可以创建一个仅包含名称/父值的新哈希表并使用它,但我已经玩了几个小时的概念没有任何运气。

当前工作代码。

Function New-CategoryTree {
    Param (
        $Categories
    )

    $GetParentCategory = [ScriptBlock]::Create({
        Param(
            [psobject]$Category
        )
        
        #Examine the parentCategory field and see if it matches certain criteria.
        Switch ($Category.parentCategory.ref) {
            { $_ -match "^windows:([a-zA-Z_\\ 1-9]+)$" } { #if Parent Category matches 'Windows:*'
                Return "$($Category.parentCategory.ref)\$($Category.name)"
            }
            { [String]::IsNullOrWhiteSpace($_) } { #If pareent
                Return
            }
            Default {
                Return ("$(& $GetParentCategory -Category ($Categories.where({$_.name -eq $Category.parentCategory.ref})))\$($Category.name)")
            }
        }
    })

    New-Variable -Name Result -Value (New-Object -TypeName System.Collections.ArrayList)
    New-Variable -Name NewCategories -Value (New-Object -TypeName System.Collections.ArrayList)
    ForEach ($Category in $Categories) {
        [Void]$NewCategories.Add((& $GetParentCategory -Category $Category))
    }

    ForEach ($Category in $NewCategories) {
        ([Regex]::Match($Category,'^windows:([a-zA-Z_\\ 1-9]+)$').groups[1]).where({$_.success -eq $True}).value |ForEach-Object {[Void]$Result.Add($_)}
    }
    Return $Result
}

数据集

<categories>
    <category name="InternetExplorer" displayName="$(string.InternetExplorer)" explainText="$(string.IE_ExplainCat)">
        <parentCategory ref="windows:WindowsComponents" />
    </category>
    <category name="AdvancedPage" displayName="$(string.AdvancedPage)">
        <parentCategory ref="InternetCPL" />
    </category>
    <category name="InternetCPL_Advanced_Accessibility" displayName="$(string.InternetCPL_Advanced_Accessibility)">
        <parentCategory ref="AdvancedPage" />
    </category>
    <category name="InternetCPL_Advanced_International" displayName="$(string.InternetCPL_Advanced_International)">
        <parentCategory ref="AdvancedPage" />
    </category>
    <category name="InternetCPL_Advanced_Security" displayName="$(string.InternetCPL_Advanced_Security)">
        <parentCategory ref="AdvancedPage" />
    </category>
</categories>

预期输出

WindowsComponents\InternetExplorer
WindowsComponents\RSS_Feeds
WindowsComponents\InternetExplorer\InternetCPL\AdvancedPage\InternetCPL_Advanced_Accessibility
WindowsComponents\InternetExplorer\InternetCPL\AdvancedPage\InternetCPL_Advanced_International
WindowsComponents\InternetExplorer\InternetCPL\AdvancedPage\InternetCPL_Advanced_Security
WindowsComponents\InternetExplorer\InternetCPL\InternetCPL_Connections
WindowsComponents\InternetExplorer\InternetCPL\InternetCPL_Content
WindowsComponents\InternetExplorer\InternetCPL\InternetCPL_Content\InternetCPL_Content_Certificates
WindowsComponents\InternetExplorer\InternetCPL\InternetCPL_Privacy
WindowsComponents\InternetExplorer\InternetCPL\InternetCPL_Programs
WindowsComponents\InternetExplorer\InternetSettings\Advanced\Browsing
WindowsComponents\InternetExplorer\InternetSettings\Advanced\ICWSettings
WindowsComponents\InternetExplorer\InternetSettings\Advanced\Multimedia
WindowsComponents\InternetExplorer\InternetSettings\Advanced\Printing
WindowsComponents\InternetExplorer\InternetSettings\Advanced\Searching
WindowsComponents\InternetExplorer\InternetSettings\Advanced\SignupSettings
WindowsComponents\InternetExplorer\CategoryAppCompat\ScriptPaste
WindowsComponents\InternetExplorer\InternetSettings\ComponentUpdates\HelpAbout128
WindowsComponents\InternetExplorer\InternetSettings\ComponentUpdates\UpdateCheck
WindowsComponents\InternetExplorer\CorporateSettings\CodeDownload
WindowsComponents\InternetExplorer\InternetSettings\DisplaySettings\GeneralColors
WindowsComponents\InternetExplorer\InternetSettings\DisplaySettings\LinkColors
WindowsComponents\InternetExplorer\InternetCPL\AdvancedPage
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryNetworkProtocolLockdown\IESF_NPLRest_Category
WindowsComponents\InternetExplorer\AdminApproved
WindowsComponents\InternetExplorer\CategoryAppCompat
WindowsComponents\InternetExplorer\Channels
WindowsComponents\InternetExplorer\CorporateSettings
WindowsComponents\InternetExplorer\DeleteBrowsingHistory
WindowsComponents\InternetExplorer\InternetCPL
WindowsComponents\InternetExplorer\InternetSettings
WindowsComponents\InternetExplorer\Menus
WindowsComponents\InternetExplorer\Persistence
WindowsComponents\InternetExplorer\SecurityFeatures
WindowsComponents\InternetExplorer\Toolbars
WindowsComponents\InternetExplorer\InternetSettings\Advanced
WindowsComponents\InternetExplorer\InternetSettings\AutoCompleteCat
WindowsComponents\InternetExplorer\InternetSettings\ComponentUpdates
WindowsComponents\InternetExplorer\InternetSettings\DisplaySettings
WindowsComponents\InternetExplorer\InternetSettings\Encoding
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_InternetZone
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_InternetZoneLockdown
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_IntranetZone
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_IntranetZoneLockdown
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_LocalMachineZone
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_LocalMachineZoneLockdown
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_RestrictedSitesZone
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_RestrictedSitesZoneLockdown
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_TrustedSitesZone
WindowsComponents\InternetExplorer\InternetCPL\IZ_SecurityPage\IZ_TrustedSitesZoneLockdown
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_AddOnManagement
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryAJAX
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryBinaryBehaviorSecurityRestriction
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryConsistentMimeHandling
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryInformationBar
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryLocalMachineZoneLockdownSecurity
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryMimeSniffingSafetyFeature
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryMKProtocolSecurityRestriction
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryNetworkProtocolLockdown
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryObjectCachingProtection
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryProtectionFromZoneElevation
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryRestrictActiveXInstall
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryRestrictFileDownload
WindowsComponents\InternetExplorer\SecurityFeatures\IESF_CategoryScriptedWindowSecurityRestrictions
WindowsComponents\InternetExplorer\CategoryPrivacy
WindowsComponents\InternetExplorer\CategoryAccelerators
WindowsComponents\InternetExplorer\CategoryCompatView
WindowsComponents\InternetExplorer\InternetCPL\CategoryGeneralPage
WindowsComponents\InternetExplorer\InternetCPL\CategoryGeneralPage\CategoryBrowsingHistory

解决方法

首先正确处理您的 xml 数据,以便您可以与之交互:

[xml]$categories

然后就可以轻松显示了:

[xml]$categories.categories.category | 
    select @{l='ParentCategory';e={$_.ParentCategory.ref}},Name,Displayname

ParentCategory            name                              
--------------            ----                              
windows:WindowsComponents InternetExplorer                  
InternetCPL               AdvancedPage                      
AdvancedPage              InternetCPL_Advanced_Accessibility
AdvancedPage              InternetCPL_Advanced_International
AdvancedPage              InternetCPL_Advanced_Security

根据需要过滤它:

$filtered = [xml]$categories.categories.category | 
    where {$_.ParentCategory.ref -match '^windows:([a-zA-Z_\\ 1-9]+)$'}
$filtered

name             displayName                explainText             parentCategory
----             -----------                -----------             --------------
InternetExplorer $(string.InternetExplorer) $(string.IE_ExplainCat) parentCategory

并将过滤后的 xml 对象导出回字符串,添加外部节点:

$xmlout = '<categories>'+$filtered.outerxml+'</categories>'
,

经过几个小时的研究,我偶然发现了“systems.collections.generic.dictionary”属性,它使我能够从本质上创建一个以 PSCustomObject 作为值的哈希表。这使我能够创建一个具有可引用名称的新对象,从而避免使用搜索功能。结合新的数据类型 + 使用 Streamreader 读取文件,我的脚本从大约 3-5s 到大约 0.5s p.s.忽略我在代码中的所有注释,我正在努力将我的头脑围绕在函数 lol 上。

Function New-CategoryTree {
    Param (
        $Categories
    )
        
    #Scriptblock that will be used to check if the currently returned object is the root object.
    $GetParentCategory = [ScriptBlock]::Create({
        Param(
            [Parameter(mandatory=$True)]
            $Category,[Parameter(mandatory=$True)]
            $Categories
        )
        Switch -regex ($Category.ParentCategory) {
            "^windows:([a-zA-Z_\\ 1-9]+)$" { #if Category matches 'Windows:*' (a.k.a. we are done with the dive.)
                Return "$($Category.ParentCategory)\$($Category.DisplayName)"
            }
            "/^$|\s+/"  { #Check if whitespace or empty.
                Write-Host "Warning: This shouldn't be possible,best guess is ADMX is missconfigured. CategoryName: '$($Category.Name)'."
                #This means its a root category without a parent so just return.
                Return
            }
            Default {#If not root category,then restart the loop to dive 1 layer deeper then eventually retun with parentCategory.DisplayName\Category.DisplayName.
                #If there is no valid parent category then thow a ignorable warning.
                If ([String]::IsNullOrEmpty($Categories["$($Category.ParentCategory)"])) {
                    Write-Host "Warning: $($Category.name) has no valid parent category."
                } Else {
                    Return ("$(& $GetParentCategory -Category $Categories["$($Category.ParentCategory)"] -Categories $Categories)\$($Category.displayName)")
                }
            }
        }
    })

    New-Variable -Name Results -Value (New-Object -TypeName System.Collections.Generic.List[String]) -Force
    ForEach ($Category in $Categories.GetEnumerator()) {
        $Results.Add((& $GetParentCategory -Category $Category.Value -Categories $Categories))
    }
    Return $Results
}

#Start Looping through every ADMX files.
ForEach ($File in $Script.ADMXFiles) {
    #Get content of ADMX file and store results as XML
    Set-Variable -Name ADMXFile      -Value ([xml]((New-Object -TypeName System.IO.StreamReader -ArgumentList $File.FullName,([Text.Encoding]::Default),$False,"10000").ReadToEnd()))
    New-Variable -Name Categories -Value (New-Object -TypeName 'System.Collections.Generic.Dictionary[[string],[PSCustomObject]]') -Force
    $ADMXFile.policyDefinitions.categories.Category |ForEach-Object {
        $Categories.add($_.name,[PSCustomObject]@{
            Name           = $_.name
            DisplayName    = ConvertFrom-StringTable -String $_.displayName -ADMX ($File.BaseName)
            ParentCategory = $_.ParentCategory.ref
        })
    }
    New-CategoryTree -Categories $Categories
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-