Skip to content

Regarding String.replace #10178

@vjay82

Description

@vjay82

Hi,

as a follow up on #10170 (comment) I experimented a bit:

https://jsbenchmark.com/#eyJjYXNlcyI6W3siaWQiOiJWTXJCVVlXWW85SUZnb3l2Q3d2OUIiLCJjb2RlIjoidmFyIGEgPSBcInRoaXMgaXMgYSB0ZXN0IHN0cmluZ1wiICsgTWF0aC5yYW5kb20oKTsgdmFyIGIgPSBcImFhJGJiXCIgKyBNYXRoLnJhbmRvbSgpOyBhLnJlcGxhY2VBbGwoXCJpXCIsIGIucmVwbGFjZUFsbChcIiRcIiwgXCIkJCQkXCIpKSIsIm5hbWUiOiJ0d2ljZSB3aXRoIGRvbGxhciIsImRlcGVuZGVuY2llcyI6W119LHsiaWQiOiJIYV9wUjZNLU1uOGpRbG9uQmZRcmQiLCJjb2RlIjoidmFyIGEgPSBcInRoaXMgaXMgYSB0ZXN0IHN0cmluZ1wiICsgTWF0aC5yYW5kb20oKTsgdmFyIGIgPSBcImFhc2JiXCIgKyBNYXRoLnJhbmRvbSgpOyBhLnJlcGxhY2VBbGwoXCJpXCIsIGIucmVwbGFjZUFsbChcIiRcIiwgXCIkJCQkXCIpKSIsIm5hbWUiOiJ0d2ljZSB3aXRob3V0IGRvbGxhciIsImRlcGVuZGVuY2llcyI6W119LHsiaWQiOiJ2UTAzdVA5Vy1DYWptOHVXdUhOX24iLCJjb2RlIjoidmFyIGEgPSBcInRoaXMgaXMgYSB0ZXN0IHN0cmluZ1wiICsgTWF0aC5yYW5kb20oKTsgdmFyIGIgPSBcImFhc2JiXCIgKyBNYXRoLnJhbmRvbSgpOyAgYS5yZXBsYWNlQWxsKFwiaVwiLCBiKSIsIm5hbWUiOiJmYXN0UGF0aCIsImRlcGVuZGVuY2llcyI6W119LHsiaWQiOiJOb0lPNVV5NDFucnVWNThCUk9HVk8iLCJjb2RlIjoidmFyIGEgPSBcInRoaXMgaXMgYSB0ZXN0IHN0cmluZ1wiICsgTWF0aC5yYW5kb20oKTsgdmFyIGIgPSBcImFhJGJiXCIgKyBNYXRoLnJhbmRvbSgpOyBhLnJlcGxhY2VBbGwoXCJpXCIsIGZ1bmN0aW9uKCkge3JldHVybiBifSkiLCJuYW1lIjoiZnVuY3Rpb24iLCJkZXBlbmRlbmNpZXMiOltdfSx7ImlkIjoianlTWElWR21rdldEVzZDNlFJVXBwIiwiY29kZSI6InZhciBhID0gXCJ0aGlzIGlzIGEgdGVzdCBzdHJpbmdcIiArIE1hdGgucmFuZG9tKCk7IHZhciBiID0gXCJhYSRiYlwiICsgTWF0aC5yYW5kb20oKTsgYS5yZXBsYWNlQWxsKFwiaVwiLCAoKSA9PiB7cmV0dXJuIGJ9KSIsIm5hbWUiOiJsYW1iZGEiLCJkZXBlbmRlbmNpZXMiOltdfV0sImNvbmZpZyI6eyJuYW1lIjoiQmFzaWMgZXhhbXBsZSIsInBhcmFsbGVsIjp0cnVlLCJnbG9iYWxUZXN0Q29uZmlnIjp7ImRlcGVuZGVuY2llcyI6W119LCJkYXRhQ29kZSI6IiJ9fQ

On my machine "function"/"lambda" seems to be the overall winner.
("fastPath" wins in Firefox in case of constant input strings but not in Chrome.)

So my proposal would be something like this:

	public String replace(CharSequence from, CharSequence to) {
		return asNativeString().replaceAll(from.toString(), () -> {
			return to.toString();
		});
	}

Regards

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions