Skip to content

Commit e581d69

Browse files
Merge pull request #511 from campersau/perf1
Use backwards for loop instead of linq for performance in AttributeCollection.Remove
2 parents 2e98e14 + 0e4d99e commit e581d69

2 files changed

Lines changed: 20 additions & 9 deletions

File tree

src/HtmlAgilityPack.Shared/HtmlAttributeCollection.cs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
using System;
99
using System.Collections;
1010
using System.Collections.Generic;
11-
using System.Linq;
1211

1312
namespace HtmlAgilityPack
1413
{
@@ -368,20 +367,14 @@ public void Remove(string name)
368367
throw new ArgumentNullException("name");
369368
}
370369

371-
List<int> listToRemove = new List<int>();
372-
for (int i = 0; i < items.Count; i++)
370+
for (int i = items.Count - 1; i >= 0; i--)
373371
{
374372
HtmlAttribute att = items[i];
375373
if (String.Equals(att.Name, name, StringComparison.OrdinalIgnoreCase))
376374
{
377-
listToRemove.Add(i);
375+
RemoveAt(i);
378376
}
379377
}
380-
381-
foreach(var i in listToRemove.OrderByDescending(x => x))
382-
{
383-
RemoveAt(i);
384-
}
385378
}
386379

387380
/// <summary>

src/Tests/HtmlAgilityPack.Tests.Net45/HtmlDocumentTests.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,24 @@ public void OuterHtmlHasBeenCalled_RemoveCalled_SubsequentOuterHtmlCallsAreBroke
564564
Assert.AreEqual("<html><head></head><body></body></html>", doc.DocumentNode.OuterHtml);
565565
}
566566

567+
[Test]
568+
public void TestRemoveAttribute()
569+
{
570+
var output = @"<h1>This is new heading</h1>";
571+
572+
string html = "<h1 a=\"foo\" b=\"bar\" A=\"baz\">This is new heading</h1>";
573+
574+
var htmlDoc = new HtmlDocument();
575+
htmlDoc.LoadHtml(html);
576+
577+
var h1Node = htmlDoc.DocumentNode.SelectSingleNode("//h1");
578+
579+
h1Node.Attributes.Remove("a");
580+
h1Node.Attributes.Remove("b");
581+
582+
Assert.AreEqual(h1Node.OuterHtml, output);
583+
}
584+
567585
[Test]
568586
public void TestAttributeDeEntitizeValue()
569587
{

0 commit comments

Comments
 (0)