3 ms·
> You're talking about strings here, right? This is not true in all languages, but certainly is for C :) It costs O(1) in memory to delimit strings with a null
by wyldfire 8y ago
> You're talking about strings here, right? This is not true in all languages, but certainly is for C :)
It costs O(1) in memory to delimit strings with a null terminator and O(n) in time to execute strnlen(), right? It's not free. Though, if you're lucky your string is in rodata and the compiler can calculate the sizeof() in advance, this is very-nearly-free.
EDIT: misunderstanding, disregard
- steveklabnik 8y agoOnly if your strings are null terminated; many languages do not use null termination for various reasons, and that's one of them. "Pascal strings" being the nickname, given how old this idea is, and given it was a direct competitor to C at the time.
- wyldfire 8y ago> > You really should understand how things like .size or lengh() aren’t “free” and how they work. > You're talking about strings here, right? This is not true in all languages, but certainly is for C :) I realize now that I misread this. It sounded as if you were saying '...but it is [free] for C', and on re-read I now understand that's not what you said at all.
- steveklabnik 8y agoAh, no worries! I've edited it to make it more clear, hopefully.
- hawkice 8y agoRight. But some languages prefix the string data with its length and omit the null terminator. So, depending on if the struct is passed in registers, you could say .length is free, in that it wouldn't even need a load.
- GolDDranks 8y agoThat assumes that all strings are C strings which isn't true. For example, Pascal-style strings have a size before the string data, and Rust and C++ strings have the size as metadata on stack and the string data in heap.
- steveklabnik 8y agoThis thread apparently started out as a misunderstanding, but just to show how free this can be: https://godbolt.org/z/7ehDPx https://godbolt.org/z/7ehDPx
- GolDDranks 8y agoI think you replied to the wrong post! (Thanks for the nice article btw.)
- steveklabnik 8y agoGah, you're right. Too many tabs. Thanks and you're welcome :)