Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize replace new lines for LineFormatter #542

Merged
merged 1 commit into from
Apr 15, 2015
Merged

Optimize replace new lines for LineFormatter #542

merged 1 commit into from
Apr 15, 2015

Conversation

ZhukV
Copy link
Contributor

@ZhukV ZhukV commented Apr 15, 2015

After profile code with XHProf, i find a many uses for LineFormatter::replaceNewLines. After replace calls strtr to str_replace, called time is halved.

With use strtr: http://prntscr.com/6tycs1
With use str_replace: http://prntscr.com/6tycw8

Script:

$replaceTime = 0;
$trTime = 0;

$line = "This is a testing line for benchmarking:\nstrtr vs str_replace\r\nSecond line\nThird line";

for ($i = 0; $i < 10000; $i++) {
    $time = microtime(true);
    $newLine = str_replace(["\r\n", "\n"], '', $line);
    $replaceTime += microtime(true) - $time;

    $time = microtime(true);
    $newLine = strtr($line, ["\r\n" => ' ', "\n" => ' ']);
    $trTime += microtime(true) - $time;
}

print sprintf(
    "Replace: %f\nStrtr: %s\n",
    $replaceTime,
    $trTime
);

Thank.

@Seldaek
Copy link
Owner

Seldaek commented Apr 15, 2015

Interesting, this used to be the other way around I think, but anyway the benchmark checks out so let's do this. Thanks

Seldaek added a commit that referenced this pull request Apr 15, 2015
Optimize replace new lines for LineFormatter
@Seldaek Seldaek merged commit 03fc68c into Seldaek:master Apr 15, 2015
@vlakoff
Copy link
Contributor

vlakoff commented Apr 16, 2015

If I recall correctly, strtr() is faster only for 1 to 1 character replacements. The "3 arguments" mode, doing single-byte replacements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants