When implementing a data structure like a segment tree or union find is it worth it to wrap the data structure in a class?
Will it pay off? Will the object overhead be feasible? Will the scoping play such a big role? Or maybe the typing speed?
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 151 |
When implementing a data structure like a segment tree or union find is it worth it to wrap the data structure in a class?
Will it pay off? Will the object overhead be feasible? Will the scoping play such a big role? Or maybe the typing speed?
Name |
---|
The general rule is: don't worry too much about such micro optimizations. Internally the program might have to follow a few more pointers, but not many, so your program might be <1% slower. And the odds are good that the compiler will even eliminate those overhead and you have the exact same speed.
So do you recommend the oop version?
I'm not thinking only about speed. Some problems with non-oop version are scoping which may cause clashes with other variables or just the ambiguity.
If you are worried about name clashes you could use namespaces instead, which would introduce no overhead.
Yes, I do. But keep in mind that you have only limited time in a coding contest. For that reason I also use OOP too rarely. And if I do, I usually don't use any good practices like private variables, getter, setter, ...
I prefer using OOP while implementing data structures.
There are some reasons behind this:
You can create multiple instances of your object. There are some problems where you may create, for example, more than one Fenwick tree. It's much easier to implement it if you have Fenwick tree as a class.
It may also decrease the amount of code. I remember a problem where I needed two segment trees with different operations. You need to implement it once if you put it into a class. Also this class can be made template.
The code looks much simpler and cleaner.
Classes are better when re-using code (it's helpful when you can use pre-written code on contests).
The disadvantages you noticed doesn't matter much:
Code speed. If you write on
C++
, the perfomance is nearly identical (maybe slower, maybe faster) to the implementation without OOP.Typing speed. It doesn't take much to write this, isn't it?
That's all the overhead. If you care much, you can configure your editor to generate this template automatically.
Besides, I never write treaps in OOP style (only struct
Treap
+ functions). It's more convenient for me.