Can I use :sub or :len?

Searching for some issues, I discovered that I can use the methods myVar:sub(1, 2) and myVar:len() instead of the functions string.sub(MyVar, 1, 2) and string.len(MyVar).

I just want to know if is there any problem with using the methods instead of the functions?

I ask this because I have seen many warnings about deprecated things…

myVar:sub(1, 2) is inarguably a bit slower than string.sub(myVar, 1, 2), the former invokes __index since strings have a metatable whose __index field points back to string. As for using len there is no reason to use that anymore when you should use the unary length operator #. If you need performance then don’t use :, otherwise you can take advantage of __index on strings.

2 Likes

There’s not really much of a difference, calling methods just passes self as the first argument automatically so you have to input fewer other arguments for the same purpose, strings have an __index metamethod set pointing to the string library so you can utilize its functions without calling the library explicitly.

So over a large amount of executions, method calls for strings will be slower.

the sending of this post was delayed because of an inopportune internet issue
1 Like