LightDiver, вот пример твоего кейса и наглядный пример, что ты не то оптимизируешь, никаких регэкспов не надо, все проходится прямо. Если у тебя исходные условия - не влезаешь в ограниченную память, то это тоже решабельно.
function mylen(s,n)
local count
for i = 1, n do
count = #s
end
return count
end
function u8( s )
local wstring = {}
local char = 0
for i = 1, #s do
local byte = s:byte(i)
if byte < 128 then
char = char + 1
wstring[char] = string.char(byte)
elseif byte >= 194 and byte <= 244 then
char = char + 1
if byte <= 223 then
wstring[char] = string.char(byte)..string.char(s:byte(i+1))
i = i + 1
elseif byte <= 239 then
wstring[char] = string.char(byte)..string.char(s:byte(i+1))..string.char(s:byte(i+2))
i = i + 2
else
wstring[char] = string.char(byte)..string.char(s:byte(i+1))..string.char(s:byte(i+2))..string.char(s:byte(i+3))
i = i + 3
end
end
end
return wstring
end
function benchm(s,n)
local wstring = {}
for i = 1, n do
wstring = u8( s )
end
return wstring
end
local text = "Привет ♥ мир!"
local wstring = u8(text)
local time = os.clock()
print(mylen(wstring, 100000)) --- <-- TABLE a hundred thousand iterations (omg!)
print("Прошло: " .. os.clock()-time) --- <-- as fast as native #s, since it IS native)
time = os.clock()
benchm(text, 100000) --- <-- Instantination consumes time, but once, need optimization
print("Прошло: " .. os.clock()-time)
print(text)
for i = 2, #wstring do --- <--- wow, ORLY? O_o
print( wstring[i] ) --- <--- native unicode bychar
end
./test.lua
13
Прошло: 0.002469
Прошло: 0.41051
Привет ♥ мир!
р
и
в
е
т
♥
м
и
р
!