A very unreliable bench mark shows that the browser may actually be faster. Although there may be some very large optimizations going on in the browser using the test case I made versus the PHP case I made.
This post also supports the findings: Speed of PHP vs JavaScript?
Running this code in PHP:
<?php
require("Logger.php");
$string = "apples and bananas";
$logger = new Logger("Start");
for ($x = 0; $x < 1000000; $x++) {
$newString = str_replace("bananas", "oranges", $string);
}
$logger->log("Finish");
echo $logger->status();
Came back with 10867ms on my local machine (WAMP). (And removing the class I'm using for logging does NOT speed it up.)
Running the following JS code (http://jsfiddle.net/MQKLT/3/) is returning roughly 343ms (and is visibly faster).
function go() {
var str = "apples and bananas";
var newString = "";
var d = new Date();
var n = (d.getSeconds() * 1000) + d.getMilliseconds();
for (var x = 0; x < 1000000; x++) {
newString = str.replace("bananas", "oranges");
newString = newString + x;
}
var d2 = new Date();
var n2 = (d2 .getSeconds() * 1000) + d2.getMilliseconds();
//console.log("First: " + n + " Second: " + n2 + " Total: " + (n2 - n));
alert("First: " + n + " Second: " + n2 + " Total: " + (n2 - n) + " Output: " + newString);
}
As I said, the browser may be doing some major optimizations. The value I posted above was tested in Chrome. I do get similar times in IE and a faster time in Firefox (which suggests to me that optimizations are happening.)
With that in mind:
I'm a lazy programmer and I tend to go with what is most convenient for me as long as it doesn't compromise security. (IE, string manipulation in regards to validation should be done in PHP / away from client control) It makes absolutely no sense to do an AJAX request for a string replace by itself. For real world cases it depends on a lot of variables such as the browser involved, the PC involved, the server involved.
If you are worried about string replace performance, there is likely something wrong with the logic you are using to perform your task.