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 | orzdevinwang | 3844 |
3 | jqdai0815 | 3682 |
4 | jiangly | 3618 |
5 | Benq | 3529 |
6 | ksun48 | 3489 |
7 | Radewoosh | 3483 |
8 | Kevin114514 | 3443 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | atcoder_official | 162 |
3 | maomao90 | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | djm03178 | 152 |
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.