Re: slow startup on windows

Jeroen van der Zijp <[email protected]> Sun, 27 Oct 2024 09:53:34 -0500
Newsgroups gmane.comp.lib.fox-toolkit.user
Organization FOX Toolkit
Message-ID <[email protected]>
> > I've traced it back to this command where I'm creating an array
> > of classes (Material). This loop:
> >
> > 	FXArray<Material> array;
> > 	Material str;
> >
> > 	for (long i = 0; i < 30000; i++)
> > 	{
> > 		array.append(str);
> > 	}
> >
> >
> > takes about 10 s on Windows and about 1 s on Windows.
> >
> > If I use a simpler class (something smaller than the " Material"
> > class) it goes faster.
> >
> > To me this indicates that it's a compiler problem. I'm assuming
> > only the compiler is involved in copy classes. Unless something
> > is different in the implementation of FXArray.

This is extremely dumb code.  If you know there are going to be 30,000
elements, allocate for 30,000 right from the start and then you can 
populate the array with no resizing.

Growing an array one-by-one is O(N^2) because every time an element
is added, N-1 entries would be copied from the old N-1-length array
to the new N-length array. OK, sometimes, clever malloc implementations
would be able to grow a block of memory w/o data movement.  But you
shouldn't always expect it, eventually a copy will happen, and if
it happens often enough, then super-linear runtime will still result.

Its always best to pre-allocate space when you know the required
space ahead of time, or even if you can roughly estimate it [if you
over-estimate, you'll find shrinking a block is almost always very
efficient; even if a major shrink involves a reallocation, you'd
be doing it only once, and thus algorithm runtime would still be
O(N).

new code:

  FXArray<Material> array;
  Material str;

  array.no(30000);
 
  for(long i=0; i<array.no(); i++){
	array[i]=str;
  }

This would likely execute orders of magnitude faster.

Of course, if the array actually is populated with N
identical copies of str, it may be even simpler to just:

  FXArray<Material> array;
  Material str;

  array.assign(str,30000);
 
And call it a day.  This will use copy-ctor, rather than
ctor + assigment. Not knowing what default ctor or operator=()
do, combining ctor + operator=(), i.e. using copy-ctor, may
be much faster...


    -- JVZ