I heard using table.concat was faster than manual concatenation, but if you don’t want to do that you could probably do something involving formatting and repetition.
In Luau ipairs
is faster than pairs as well. If you’re using normal Lua or some other version of Lua the performance might be worse though. In that case you could use a generic for loop.
true
is outputting whether or not the strings are equal
Here’s what I was able to come up with:
-- micro optimization because indexing technically takes time
local round = math.round
local len = string.len
local sub = string.sub
local insert = table.insert
local format = string.format
local rep = string.rep
local RGB_STRING = '%d,%d,%dS'
local function coloursToListString(colours)
local formatString = rep(RGB_STRING, #colours)
local colourData = {}
for i, colour in ipairs(colours) do
local r,g,b = round(colour.R * 255), round(colour.G * 255), round(colour.B * 255)
insert(colourData, r) -- table.insert(t, element) is faster than 't[#t + 1] = element' in Luau
insert(colourData, g)
insert(colourData, b)
end
return format(sub(formatString, 1, len(formatString) - 1) --[[trim off last S]], unpack(colourData))
end
Testing code (note I switched out your math.floor with math.round
-- micro optimization because indexing technically takes time
local round = math.round
local len = string.len
local sub = string.sub
local insert = table.insert
local format = string.format
local rep = string.rep
local RGB_STRING = '%d,%d,%dS'
local function coloursToListString(colours)
local formatString = rep(RGB_STRING, #colours)
local colourData = {}
for i, colour in ipairs(colours) do
local r,g,b = round(colour.R * 255), round(colour.G * 255), round(colour.B * 255)
insert(colourData, r) -- table.insert(t, element) is faster than 't[#t + 1] = element' in Luau
insert(colourData, g)
insert(colourData, b)
end
return format(sub(formatString, 1, len(formatString) - 1) --[[trim off last S]], unpack(colourData))
end
local function ConvertColoursToListString(Colours)
local ColoursListString = ""
for i, Colour in pairs(Colours) do
local ColourR = math.round(Colour.R * 255)
local ColourG = math.round(Colour.G * 255)
local ColourB = math.round(Colour.B * 255)
local StringSegment = tostring(ColourR) .. "," .. tostring(ColourG) .. "," .. tostring(ColourB)
ColoursListString = ColoursListString .. StringSegment
if i ~= #Colours then
ColoursListString = ColoursListString .. "S"
end
end
return ColoursListString
end
local t = {}
for i = 1, 100 do
t[i] = Color3.new(math.random(), math.random(), math.random())
end
local now = os.clock()
local s = coloursToListString(t)
local _end = os.clock()
print('My method took', _end - now)
task.wait(1)
local now = os.clock()
local s2 = ConvertColoursToListString(t)
local _end = os.clock()
print('Your method took', _end - now)
print(s == s2)