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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 166 |
2 | maomao90 | 163 |
2 | Um_nik | 163 |
4 | atcoder_official | 161 |
5 | adamant | 160 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
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.