Question

Problem of Tstringlist.indexof ....too slow

Asked by: chongkeng_woon

i have 10000 ++ of numbers with some numbers are duplicate inside...but,they are not sorted in any order (neither ascending nor descending)
e.g.  num1 = {100,1234,4566,66,100,1,4566,1234,9999 ......}

i was required to remove those duplicate numbers without moving the sequence of any number, which the result should be :-

num1 = {100,1234,4566,66,1,9999 ........}

so, what i do is :

var num1,num2 :tstringlist;

for i:=0 to num1.count - 1 do begin
  if num2.indexof(num1.strings[i])<0 then begin
    num2.add(num1.strings[i]);
end;

result = num2.text;

but the problem is, it is running very slow, it need about 40++ second to finish 10000 ++ numbers .....

anotherissue is my total numbers is always changing .....sometimes, i have total 10 numbers, while sometimes might be 10000++ numbers ....

any idea ?

thanks            

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-09-24 at 04:51:21ID21143654
Tags

slow

,

tstringlist

Topic

Delphi Programming

Participating Experts
5
Points
75
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Sort this TStringList
    Can someone point me to a Delphi 2 function or procedure that will sort the contents of a TStringList in ascending and/or descending order?
  2. Listbox arrange ascending or descending?
    I have a listbox that have the function for the user to arrange it alphabertical which either ascending or descending? Is anyone know how to do it? Is it good to use Javascript. Please help me out!!
  3. sort in a predefined order (neither ascending, nor desce…
    Status Table --------------------- status ===== open reopen closed pending select * from status order by status; displays closed open pending reopen I want to display my output in an order I define. (neither ascending, nor descending) I want my output to be open r...
  4. DBGrid - TitleClick  :ascending,descending
    How do you make data ascending descending (sorted9 on dbgrid title click?
  5. Sorting a list of dates - Ascending/Descending
    I have the following structure: typedef struct nodeTag { unsigned day; unsigned mth; unsigned yrs; unsigned hrs; unsigned min; unsigned sec; struct nodeTag *next }NODE; I currently have a dynamic linked-list with all nodes containing the necessary data. However I'm now requ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Ivanov_GPosted on 2004-09-24 at 04:59:32ID: 12141858

use TStringList.CustomSort to make your own sorting routine, because comparing numbers as string is not very accurate...

 

by: Ferruccio68Posted on 2004-09-24 at 05:28:20ID: 12142062

Why don't you simply use TSTringList.Duplicates :=  dupIgnore;

procedure TForm1.Button1Click(Sender: TObject);
var
  List : TStringList;
  i  : integer;
begin
  List := TStringList.Create;
  List.Duplicates := dupIgnore;
  List.Sorted := true;
  List.LoadFromFile('FileName'); //or just add NUM1 as text
   
  for i := 0 to List.Count - 1 do
  begin
    //DO whatever you want
  end;

  List.Free;
end;

 

by: Workshop_AlexPosted on 2004-09-24 at 05:48:55ID: 12142244

@Ferruccio68, dupIgnore does nothing if the stringlist is not sorted. And if I understand correctly, this list cannot be sorted.

@hongkeng_woon, why did you ever decide to use a stringlist for storing numbers in the first place? It would be a lot easier if you would store them in a dynamic array of integers in the first place. Or a TList if using dynamic arrays is too complex for you. If you use numbers only, store them as numbers! Then the comparisons will be a lot faster too.
At http://www.workshop-alex.org/Sources/untDuplicateCheck.pas you will find an interesting unit called untDuplicateCheck, written by me. Basically, it provides a mechanism to check for duplicates, and it does this quite fast. Use something like:

var
  DuplicateChecker: IDuplicateChecker;
  I: Integer;
begin
  DuplicateChecker:= NewDuplicateChecker; // Parameters are all optional.
  for i:=0 to num1.count - 1 do begin
    if AddAndCheck(num1.strings[i]) then num2.add(num1.strings[i]);
  end;
  DuplicateChecker:= nil;
end;

Above code will probably perform "slightly" faster... ;-)

 

by: Workshop_AlexPosted on 2004-09-24 at 05:51:10ID: 12142265

One minor warning, though... Speed comes at a price. My method will eat a lot of memory. It takes 10 megabytes of memory when active. But the memory will be freed again once you're done and assigned nil to the duplicate checker. It's the price you have to pay for a very neat speed increase...

 

by: Workshop_AlexPosted on 2004-09-24 at 06:02:41ID: 12142377

if AddAndCheck(num1.strings[i]) then num2.add(num1.strings[i]);

Should be:

if DuplicateChecker.AddAndCheck(num1.strings[i]) then num2.add(num1.strings[i]);

Silly me... :-)

 

by: Ferruccio68Posted on 2004-09-24 at 06:03:30ID: 12142385

--> @Ferruccio68, dupIgnore does nothing if the stringlist is not sorted. And if I understand correctly, this list cannot be sorted.
Gosh,i've totally misreaded the question! :((

 

by: Ferruccio68Posted on 2004-09-24 at 06:08:09ID: 12142444

Well, just a test....
Using Pos instead of indexof seems to be more fast.
This is quite fast using listboxes, so i guess that using STringLIsts missing the drawing should be more fast again

procedure TForm1.Button1Click(Sender: TObject);
var
i,y: Integer;
begin
for i := 1 to 3 do
   for y := 1 to 10000 do
     if y mod 2 = 0 then
      Listbox1.Items.Add(inttostr(y))
     else
      Listbox1.Items.Insert(Y-1,inttostr(y))
end;

procedure TForm1.Button2Click(Sender: TObject);
var
i: Integer;
s: STring;
begin
for i := 0 to Listbox1.Items.Count-1 do
begin
  If pos(Listbox1.Items[i],s) = 0 then
   s := s+Listbox1.Items[i]+',';
 end;
 ListBox2.Items.CommaText := s;
end;

 

by: gary_williamsPosted on 2004-09-24 at 06:42:33ID: 12142929


function SortCompare2(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := Integer(List.Objects[Index1]) - Integer(List.Objects[Index2]);
end;

function SortCompare1(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := CompareText(List[Index1], List[Index2]);
  if (Result = 0) then
    Result := SortCompare2(List, Index1, Index2);
end;

{
  This procedure assumes the Objects property of the string list is unpopulated.
}
procedure RemoveDuplicatesFromStringListWhilePreservingOriginalOrder(const SL: TStringList);
var
  I: Integer;
begin
  SL.CommaText;
 
  for I := 0 to (SL.Count - 1) do
    SL.Objects[I] := TObject(I);

  SL.CustomSort(SortCompare1);

  for I := (SL.Count - 1) downto 1 do
    if (SL[I] = (SL[I - 1])) then
      begin
      Assert(Integer(SL.Objects[I]) > Integer(SL.Objects[I - 1]));
      SL.Delete(I);
      end;

  SL.CustomSort(SortCompare2);

  for I := 0 to (SL.Count - 1) do
    SL.Objects[I] := nil;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    SL.Assign(Memo1.Lines);
    RemoveDuplicatesFromStringListWhilePreservingOriginalOrder(SL);
    Memo2.Lines.Assign(SL);
  finally
    SL.Free;
  end;
end;

 

by: gary_williamsPosted on 2004-09-24 at 06:48:11ID: 12143012

My solution avoids IndexOf completely.  SortCompare1 alphabetizes the list, and SortCompare2 restores the original sequence.  The original sequence is temporarily stuffed into the Objects property of the list, so this is only appropriate when you're not already using the Objects property.

 

by: gary_williamsPosted on 2004-09-24 at 06:49:41ID: 12143029

You can remove the reference to   SL.CommaText; in my solution, it was only put in temporarily for debugging as the linker removed the method and I wanted to watch the sequence in the debugger.  I just forgot to remove it.

 

by: gary_williamsPosted on 2004-09-24 at 06:50:29ID: 12143039

You can also remove the Assert.  Sorry about that.

 

by: tzxie2000Posted on 2004-09-25 at 09:23:48ID: 12151000

suggest you change string to int as string compare is veryvery slow
the code is like below
I want to check the time it run but it runs so quick(not more than 1second) so I did not check the time

procedure TForm1.Button1Click(Sender: TObject);
var
  i,j:integer;
  s:string;
  dt:TDateTime;
  sl:TStrings;
  na:array[0..10000] of integer;
  found:boolean;
  tempi:integer;
begin
  s:='';
  s:=IntToStr(random(10000));
  for i := 2 to 10000 do
  begin
    s:=s+','+IntToStr(random(10000));
  end;
  dt:=Now;
  sl:=TStringList.Create;
  sl.QuoteChar:=',';
  sl.DelimitedText:=s;
  for i:=0 to sl.Count-1 do
  begin
    na[i]:=StrToInt(sl[i]);
  end;
  s:=IntToStr(na[0]);
  for i:=1 to sl.Count-1 do
  begin
    found:=false;
    for j:=i+1 to sl.Count-1 do
    begin
      if(na[j]=na[i])then
      begin
        found:=true;
        break;
      end;
    end;
      if not found then
      begin
        s:=s+','+IntToStr(na[i]);
      end;
  end;
AppliCation.MessageBox(PChar(s),'');
end;

 

by: Workshop_AlexPosted on 2004-09-25 at 16:15:01ID: 12152434

As I see it, chongkeng_woon is moving strings from one stringlist to the second one but wants to skip all duplicates. One other alternatives would be by using two stringlists, adding each value to both of them. One sorted list and one unsorted list. With the sorted list you could use the IndexOf property to see if it's already added.

var num1,num2, num3 :tstringlist;

num2 := TStringList.Create;
num2.Sorted := False;
num3 := TStringList.Create;
num3.Sorted := True;
num3.Duplicates=dupIgnore;
for i:=0 to num1.count - 1 do begin
  if num3.indexof(num1.strings[i])<0 then begin
    num2.add(num1.strings[i]);
    num3.add(num1.strings[i]);
  end;
end;
num3.Free;

Then num2 is your list of items in the preferred order and num3 is just there to check for duplicates. But again, this is what I used my duplicateCheck unit for, which tends to be a bit faster.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...