4 ms·
Using Strings in any performance-critical situation, like object identifiers, is a newbie mistake (but also extremely common). That one shouldn't have happened.
by coldpie 4y ago
Using Strings in any performance-critical situation, like object identifiers, is a newbie mistake (but also extremely common). That one shouldn't have happened. The others just strike me as things one learns about and fixes as the project matures and someone bothers to do a perf analysis to find the low-hanging fruit.
- hnthrowaway0315 4y agoThanks! Is the reason Strings impact performance because we can use smaller objects to do such work while Strings are larger?
- coldpie 4y agoBasically yeah. At a super rough level of understanding, the CPU can compare two integers with one instruction, but has to loop through a whole string[1] one character at a time to compare two strings for equality. [1] Yeah yeah, CPUs & standard libraries are smarter than that, I know, I know. You get the point.
- saagarjha 4y agoMost String comparisons are <5 instructions
- stefncb 4y agoIt's not necessarily about the size itself, but more about the fact that it has to go through a memory allocator and it has to be GC'd if that's applicable, while a simple integer doesn't. Copies are more involved too. Using strings for identifiers is almost always a bad idea.
- soiler 4y agoNot something I had considered. So for example a UI component that might load 3 different versions based on a string identifier, should instead use an enum which maps to integers? I say an enum because this would preserve readability of the code.
- coldpie 4y agoDo you mean an API entirely internal to your application? In that case, yes, you probably want to use integers (enums), not Strings, to choose what to display. If you are interfacing with other APIs that use Strings, it may make sense to just pass those through. For example loading files from disk or pulling up UI classes from the OS library using some String identifier or something. It's hard to say without more context.
- soiler 4y agoYes I was referring to internal APIs. Thanks
- saagarjha 4y agoThis is not true on iOS for most strings.
- stefncb 4y agoWhy is that?
- sixstringtheory 4y agoMy guess is they are talking about some optimizations iOS does to make strings more performant, like interned string constants and tagged pointers. The majority of string usage probably falls under those. Working with dynamically allocated strings, like reading from files, rendering from data bytes, working with C strings or building formatted strings, might have worse performance characteristics.
- saagarjha 4y ago…this is not very good advice? Using strings is fine, until it becomes a problem. People are going to read your comment and decide to change all their strings to integers or something at the cost of maintainability.