Quantcast
Channel: Why use getters and setters/accessors? - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by kangalio for Why use getters and setters/accessors?

$
0
0

I know it's a bit late, but I think there are some people who are interested in performance.

I've done a little performance test. I wrote a class "NumberHolder" which, well, holds an Integer. You can either read that Integer by using the getter methodanInstance.getNumber() or by directly accessing the number by using anInstance.number. My programm reads the number 1,000,000,000 times, via both ways. That process is repeated five times and the time is printed. I've got the following result:

Time 1: 953ms, Time 2: 741msTime 1: 655ms, Time 2: 743msTime 1: 656ms, Time 2: 634msTime 1: 637ms, Time 2: 629msTime 1: 633ms, Time 2: 625ms

(Time 1 is the direct way, Time 2 is the getter)

You see, the getter is (almost) always a bit faster. Then I tried with different numbers of cycles. Instead of 1 million, I used 10 million and 0.1 million.The results:

10 million cycles:

Time 1: 6382ms, Time 2: 6351msTime 1: 6363ms, Time 2: 6351msTime 1: 6350ms, Time 2: 6363msTime 1: 6353ms, Time 2: 6357msTime 1: 6348ms, Time 2: 6354ms

With 10 million cycles, the times are almost the same.Here are 100 thousand (0.1 million) cycles:

Time 1: 77ms, Time 2: 73msTime 1: 94ms, Time 2: 65msTime 1: 67ms, Time 2: 63msTime 1: 65ms, Time 2: 65msTime 1: 66ms, Time 2: 63ms

Also with different amounts of cycles, the getter is a little bit faster than the regular way. I hope this helped you.


Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>