Skip to content

Instantly share code, notes, and snippets.

@Kampfkarren
Created November 14, 2024 18:13
Show Gist options
  • Save Kampfkarren/fbfc4febb3a9ec77fed02e8ed1332c8f to your computer and use it in GitHub Desktop.
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
local ESCAPES: { [string]: string? } = {
["&"] = "&",
["<"] = "&lt;",
[">"] = "&gt;",
['"'] = "&quot;",
["'"] = "&apos;",
}
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 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("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"):gsub('"', "&quot;"):gsub("'", "&apos;"))
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,
},
}
@Kampfkarren
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment