Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> 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



Only 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.


> > 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.


Ah, no worries! I've edited it to make it more clear, hopefully.


Right. 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.


That 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.


This thread apparently started out as a misunderstanding, but just to show how free this can be: https://godbolt.org/z/7ehDPx


I think you replied to the wrong post! (Thanks for the nice article btw.)


Gah, you're right. Too many tabs. Thanks and you're welcome :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: