How to loop through characters of a string in D language?
rumbu
rumbu at rumbu.ro
Thu Dec 23 16:23:32 UTC 2021
On Thursday, 23 December 2021 at 07:14:35 UTC, Salih Dincer wrote:
> It seems faster than algorithms in Phobos. We would love to see
> this in our new Phobos.
> Replace: 436 msecs
> Malloc : 259 msecs
> */
It seems because MallocReplace is cheating a lot:
- it is not called through another function like replace is
called;
- accesses directly the constant str;
- assumes that it has a single character to replace;
- assumes that the character will be deleted not replaced with
something;
- assumes that the character is always ';'
- assumes that the replacing string is not bigger than the
replaced one, so it knows exactly how much space to allocate;
- does not have any parameter, at least on x86 this means that
there is no arg pushes when it's called.
- does not return a string, just compares its result with another
constant;
Since we already know all this stuff, we can go further :)
```d
string superFast()
{
enum r = str.replace(";", "");
return r;
}
```
> Replace: 436 msecs
> Malloc : 259 msecs
> SuperFast: 0 msecs
More information about the Digitalmars-d-learn
mailing list