slow runtime

Jonathan M Davis jmdavisprog at gmail.com
Thu Sep 9 20:09:39 PDT 2010


On Thursday 09 September 2010 19:40:47 Dr. Smith wrote:
> The class code below runs terribly slow.  Conversely, when converted into a
> function (albeit returning only one value), it runs fast.  Any insights
> into this or suggestions to get a function to return multiple types at
> once?
> 
> ...library code...
> 
> module testlib;
> import std.stdio, std.string;
> 
> class classtest {
> 
>   int i, j;
> 
>   double[][] hit() {
> 
>     double[][] hi = new double[][](1000, 40);
> 
>     for(i = 1; i < 1000; i++) {
>       for(j = 1; j < 40; j++) {
>         hi[i][j] = (i);
>       }
>     }
>     return hi;
>   }
> 
>   double[][] hot() {
> 
>     double[][] ho = new double[][](1000, 40);
> 
>     for(i = 1; i < 1000; i++) {
>       for(j = 1; j < 40; j++) {
>         ho[i][j] = (j);
>       }
>     }
>     return ho;
>   }
> 
>   string stest () {
>     string hello = "yo!";
>     return hello;
>   }
> }
> 
> ... calling code ...
> 
> import std.stdio, std.string;
> import testlib;
> 
> void main() {
> 
>   classtest obj = new classtest;
>   int i, j;
> 
>   for(i = 1; i < obj.hit.length; i++) {
>     for(j = 1; j < obj.hit[i].length; j++) {
>       writefln("%s\t%f\t%f", obj.stest, obj.hit[i][j], obj.hot[i][j]);
>     }
>   }
> }


Ouch. Woh. And ouch. LOL. Do you realize that _every time_ that you use hit or 
hot in main(), you're calling hit() and hot() and creating them all over again? 
Currently, functions which don't take any parameters and return a value and 
functions which take a single paramater and don't return anything are callable 
as if they were member variables. The correct way to do this is to mark them 
with @property, and eventually functions not marked with @property won't be 
useable as properties (so you'll have to call them explicitly), and functions 
marked with @property will have to be used as properties rathen than called 
explicitly, but dmd hasn't been updated to that point yet.

If you were to just assign hit() and hot() to local variables which you called, 
it would be a _lot_ faster. Now, it makes no sense for i or j to be member 
variables of your class since you just reset them every time that you use them, 
and it makes no sense for any of your functions to be part of a class, so they 
don't use any state from the class, but that's a separate issue. The problem 
here is that you keep calling hit() and hot() over and over. You end up with on 
O(n^4) algorithm instead of O(n^2). Painful indeed.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list