Skip to content

Instantly share code, notes, and snippets.

echiesse/StringPerformance.lua Last active Nov 30, 2017

Performance benchmark for string replacement in lua
 -- Functions based on this problem: http://rosalind.info/problems/revc/ complements = { A = "T", T = "A", C = "G", G = "C", } -- Slow implementation function dnaRev1(s) local s2 = "" for c in string.gmatch(s, ".") do s2 = complements[c] .. s2 end return s2 end -- Fast implementation function dnaRev2(s) local comp = string.gsub(s, ".", complements) return comp:reverse() end -- Decent, but not so fast implementation function dnaRev3(s) local comp = string.gsub(s, ".", complements) local array = explode(comp) local n = #array for i = 1, n/2 do array[i], array[n - i + 1] = array[n - i + 1], array[i] end return table.concat(array) end --############################################################################## -- Support: function randomString(chars, length) local buffer = {} for i = 1, length do table.insert(buffer, chars[math.random(1, #chars)]) end return table.concat(buffer) end function explode(str) local ret = {} for i = 1, #str do table.insert(ret, string.sub(str, i, i)) end return ret end function withTimer(callback, ...) t = {os.time()} local ret = {callback(...)} t[2] = os.time() return t, unpack(ret) end function logTime(iniMessage, callback, ...) print(iniMessage) local ret = {withTimer(callback, ...)} local t = ret[1] print("Tempo: " .. t[2] - t[1]) table.remove(ret, 1) return unpack(ret) end --############################################################################## -- Teste: seq = randomString(explode("ACTG"), 500000) s1 = logTime("Calculando sequencia 1 (concatenando)", dnaRev1, seq) s2 = logTime("Calculando sequencia 2 (string.gsub)", dnaRev2, seq) s3 = logTime("Calculando sequencia 3 (custom reverse)", dnaRev3, seq) print(s1 == s2) print(s3 == s2)
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.