[DGD] Reasonable Tick Counts?

Mikael Lind mikkelin at gmail.com
Mon Jul 9 09:17:34 CEST 2007


Hello Kurt,

If you are worried about efficiency you can perhaps avoid some of the
explode/implode replacements by checking with sscanf() first. You may
want to benchmark this to find out if it is worthwhile. My apologies,
the following code is untested:

string replace_string(string str, string from, string to)
{
    string escaped_from; /* Snake Plissken, eat your heart out! */

    /* escape % in from */
    escaped_from = sscanf(from, "%*s%%"))
        ? implode(explode("%" + from + "%", "%"), "%%")
        : from;

    return sscanf(str, "%*s" + escaped_from)
        ? implode(explode(from + str + from, from), to)
        : str;
}

Though it could be split into subroutines at the cost of some function
call overhead:

string simple_replace_string(string str, string from, string to)
{
    return implode(explode(from + str + from, from), to);
}

string escape_sscanf_format(string format)
{
    return sscanf(format, "%*s%%")
        ? simple_replace_string(format, "%", "%%")
        : format;
}

int has_substring(string str, string sub)
{
    return sscanf(str, "%*s" + escape_sscanf_format(sub));
}

string replace_string(string str, string from, string to)
{
    return has_substring(str, from)
        ? simple_replace_string(str, from, to)
        : str;
}

Regards,
Mikael



More information about the DGD mailing list