On Friday, 4 March 2022 at 19:51:44 UTC, matheus wrote:
import std.datetime.stopwatch;
import std.stdio: write, writeln, writef, writefln;
import std;
void printStrTim(string s,StopWatch sw){
writeln("\nstr: ", s
,"\nTim(ms): ", sw.peek.total!"msecs"
,"\nTim(us): ", sw.peek.total!"usecs"
);
}
void main(){
auto sw = StopWatch(AutoStart.no);
string s, str = "4A0B1de!2C9~6";
int j;
sw.start();
for(j=0;j<1_000_000;++j){
s="";
foreach(i;str){
(i >= '0' && i <= '9') ? s~=i : null;
}
}
sw.stop();
printStrTim(s,sw);
s = "";
sw.reset();
sw.start();
for(j=0;j<1_000_000;++j){
s="";
s = str.filter!(ch => ch.isDigit).to!string;
}
sw.stop();
printStrTim(s,sw);
}
Prints:
str: 401296
Tim(ms): 306
Tim(us): 306653
str: 401296
Tim(ms): 1112
Tim(us): 1112648
-------------------------------
Unless I did something wrong (If anything please tell).
The second version involves auto-decoding, which isn't actually
needed. You can work around it with `str.byCodeUnit.filter!...`.
On my machine, times become the same then.
Typical output:
str: 401296
Tim(ms): 138
Tim(us): 138505
str: 401296
Tim(ms): 137
Tim(us): 137376