Created
November 14, 2024 18:13
-
-
Save Kampfkarren/fbfc4febb3a9ec77fed02e8ed1332c8f to your computer and use it in GitHub Desktop.
Decently optimized function for escaping rich text in Roblox. 18% faster than a naive gsub implementation in a small pessimistic case, and 53% faster in the hot case of text with no bad characters. CC0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ESCAPES: { [string]: string? } = { | |
["&"] = "&", | |
["<"] = "<", | |
[">"] = ">", | |
['"'] = """, | |
["'"] = "'", | |
} | |
local function escapeRichText(text: string): string | |
local start, finish = 1, 1 | |
local pieces = {} | |
while finish <= #text do | |
local character = string.sub(text, finish, finish) | |
local escaped = ESCAPES[character] | |
if escaped == nil then | |
finish += 1 | |
continue | |
end | |
table.insert(pieces, string.sub(text, start, finish - 1) .. escaped) | |
finish += 1 | |
start = finish | |
end | |
if start == 1 then | |
return text | |
end | |
return table.concat(pieces) .. string.sub(text, start) | |
end | |
return escapeRichText |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
This file is for use by Benchmarker (https://boatbomber.itch.io/benchmarker) | |
|WARNING| THIS RUNS IN YOUR REAL ENVIRONMENT. |WARNING| | |
--]] | |
local escapeRichTextNew = require(game.ReplicatedStorage.escapeRichTextNew) | |
local function escapeRichTextOld(text: string): string | |
return (text:gsub("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub('"', """):gsub("'", "'")) | |
end | |
return { | |
ParameterGenerator = function() | |
return | |
end, | |
Functions = { | |
["old - escape with lots of bad characters (1000x)"] = function() | |
for _ = 1, 1000 do | |
escapeRichTextOld('oh <b>my</b> "god"') | |
end | |
end, | |
["new - escape with lots of bad characters (1000x)"] = function() | |
for _ = 1, 1000 do | |
escapeRichTextNew('oh <b>my</b> "god"') | |
end | |
end, | |
["old - escape with no bad characters (1000x)"] = function() | |
for _ = 1, 1000 do | |
escapeRichTextOld("hello world") | |
end | |
end, | |
["new - escape with no bad characters (1000x)"] = function() | |
for _ = 1, 1000 do | |
escapeRichTextNew("hello world") | |
end | |
end, | |
}, | |
} |
Author
Kampfkarren
commented
Nov 14, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment