Rule request: AvoidUsingPlusEqualOnCollections
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 35/100
Línea de trabajo
Comienza con la implementación propuesta de AstVisitor y VisitAssignmentStatement; después, inspecciona Helper.Instance.GetTypeFromAnalysis() y las rutas de inicialización y análisis de tipos descritas en el issue. Define el tratamiento de collections, arrays, strings, operaciones numéricas y la condición de versión de PowerShell antes de la implementación. Se considera terminado cuando la regla informa de los casos especificados de collection += con sugerencias adecuadas al contexto, sin informar de los casos de += numérico.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Summary of the new feature
NOTE: I do believe this rule isn't relevant for v7.5+ but a lot of us are unfortunately stuck on v5.1.
As a code reviewer, I want developers to be warned about using += to build collections so that I don't have to repeatedly explain why their scripts have poor performance and can focus on reviewing logic instead of catching inefficient patterns.
Problem Statement:
Using += to build arrays and collections in PowerShell is a common performance anti-pattern. Each += operation creates an entirely new array and copies all existing elements, resulting in O(n²) complexity for building collections. This can cause significant performance degradation, especially with large datasets.
For example, adding 10,000 items to an array using += performs ~50 million copy operations, while using proper collection types performs only 10,000 add operations.
Proposed technical implementation details
Rule Name: PSAvoidUsingPlusEqualsOnCollections
Severity: Warning
Behavior:
- Skip if using PowerShell v7.5+
- Flag usage of
+=operator when the left-hand side is a collection, array, or string. - Suggest more efficient alternatives based on the context
Recommended alternatives to suggest:
- Microsoft's documentation has a good start to this:
Example violations:
# Building array with += - Flagged
$results = @()
foreach ($item in $data) {
$results += $item
}
# Building collection in loop - Flagged
$numbers = @()
for ($i = 1; $i -le 1000; $i++) {
$numbers += $i
}
# Adding to existing array - Flagged
$existingArray += $newItem
# Adding to IDictionaries
$hashtable = @{}
for ($i = 1; $i -le 1000; $i++)
{
$hashtable += @{$i = $i }
}
Should NOT be flagged:
# Numeric operations
$sum += $number
Technical Implementation:
- I plan on implementing this rule if approved.
- From my testing, the rule will inherit AstVisitor and visit
VisitAssignmentStatement. - Left-hand assignment's type can be retrieved via
Helper.Instance.GetTypeFromAnalysis() - If not found, analyze where the variable was initialized and go from there. From my testing, analyzing the right-hand side ExpressionAsts' helped determine said type if
GetTypeFromAnalysiswas unreliable. - Provide context-appropriate suggestions based on the use case
Configuration Options (up for discussion):
- Add type exclusion (e.g., String)?
What is the latest version of PSScriptAnalyzer at the point of writing
1.24.0
- Lenguaje dominante
- C#
- Estrellas
- 2.2k
- Forks
- 422
- Merge medio
- 2 h 23 min
- PR fusionados (30 d)
- 25
Preparar el entorno
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de PowerShell/PSScriptAnalyzer
-
Up-for-Grabs
Dificultad 1/5 1-3 horas Aptitud para principiantes 78/100
PowerShell/PSScriptAnalyzer#2213 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
Dificultad 4/5 1-2 días Aptitud para principiantes 18/100
PowerShell/PSScriptAnalyzer#2302 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 4/5 3-5 días Aptitud para principiantes 55/100
PowerShell/PSScriptAnalyzer#2300 ·
Los mantenedores suelen responder en 1 día
-
Invoke-ScriptAnalyzer fails intermittently with NullReferenceException in CommandInfo.ResolveParameter (ProvideCommentHelp / AvoidReservedCharInCmdlet race on Export-ModuleMember)Posiblemente ocupada @jessehouwing la tomó hace 89 días. AbiertoIssue - Bug
Dificultad 4/5 3-5 días Aptitud para principiantes 52/100
PowerShell/PSScriptAnalyzer#2229 · 6 comentarios ·
Los mantenedores suelen responder en 1 día
-
Dificultad 4/5 3-5 días Aptitud para principiantes 32/100
PowerShell/PSScriptAnalyzer#2222 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de PowerShell/PSScriptAnalyzer
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
GamaEdtech/gamatrain-back#977 ·
Los mantenedores suelen responder en 1 día
-
area-templates triage:bot-seen triage:needs-human
Dificultad 2/5 1-3 horas Aptitud para principiantes 75/100
microsoft/aspire#22356 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Needs-Triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
PowerShell/PowerShell#28432 · 1 comentario · 1 reacción ·
Los mantenedores suelen responder en 1 día
-
documentation
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
microsoft/aspire.dev#2184 ·
Los mantenedores suelen responder en 2 días
-
area-controls-refreshview platform/ios s/triaged
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
dotnet/maui#40314 · 1 reacción ·
Los mantenedores suelen responder en 1 día