Foreach-Object 与 Foreach 循环的运行时 [英] Runtime of Foreach-Object vs Foreach loop

查看:125
本文介绍了Foreach-Object 与 Foreach 循环的运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的脚本制作一个进度条,但我需要文件夹总数.

I want to do a progress bar of my script but then I need a total amount of folders.

是否存在显着的运行时差异:

Is there a significant runtime difference between:

Get-ChildItem $path -Directory | ForEach-Object {
    #do work
}

$folders = Get-ChildItem $path -Directory
foreach($folder in $folders){
    #do work
}

然后我可以使用 $folders.Count 作为我的文件夹总数.我不知道如何使用 foreach-object 循环来实现.

Then I can use $folders.Count as my total amount of folders. I don't know how to do it with a foreach-object loop.

推荐答案

管道设计用于在项目出现时立即对其进行处理,因此在管道传输时不知道列表的整个长度.

Piping is designed to process items immediately as they appear so the entire length of the list is not known while it's being piped.

Get-ChildItem $path -Directory | ForEach {
    # PROCESSING STARTS IMMEDIATELY
    # LENGTH IS NOT KNOWN
}

  • 优点:立即开始处理,无需延迟构建列表.
  • 缺点:在完全处理之前不知道列表长度
  • 另一方面,将列表分配给一个变量此时会构建整个列表,如果列表包含大量项目或构建速度很慢,例如,如果它是一个包含大量嵌套子目录的目录,或网络速度较慢的目录.

    On the other hand, assigning the list to a variable builds the entire list at this point, which can take an extremely large amount of time if the list contains lots of items or it's slow to build, for example, if it's a directory with lots of nested subdirectories, or a slow network directory.

    # BUILD THE ENTIRE LIST AND ASSIGN IT TO A VARIABLE
    $folders = Get-ChildItem $path -Directory
    # A FEW MOMENTS/SECONDS/MINUTES/HOURS LATER WE CAN PROCESS IT
    ForEach ($folder in $folders) {
        # LENGTH IS KNOWN: $folders.count
    }
    

    • 构建列表的优点 + ForEach 语句:整体花费的时间更少,因为处理 { } 块不是在每个项目上调用,而通过管道,它可以像函数或脚本块一样被调用,而这种调用开销在 PowerShell 中非常大.
    • 缺点:列表赋值语句的初始延迟可能非常大
      • Advantage of building the list + ForEach statement: overall time spent is less because processing { } block is not invoked on each item whereas with piping it is invoked like a function or scriptblock, and this invocation overhead is very big in PowerShell.
      • Disadvantage: the initial delay in the list assignment statement can be extremely huge
      • 这篇关于Foreach-Object 与 Foreach 循环的运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆