Hacker News new | ask | show | jobs
by seu 84 days ago
I'm a bit surprised to see those examples, because there's nothing really new here. These are typical beginner pitfalls and have been there for at least a decade or more. Or maybe it's because I learned java in the late 90s and later used it for J2ME, and then using things like StringBuilder (StringBuffer in the old days) were almost mandatory, and you would be very careful trying to avoid unnecessary object allocations.
2 comments

Yes, but that's not the path that modern frameworks suggest nowadays.
I remember writing Java for our introductory programming course at university around 2010. I was already familiar with object oriented programming in PHP at the time, so I just wrote the Java code like I would write PHP. I was absolutely astounded at the poor performance of the Java app. I asked one of our tutors and I can still remember him looking at the code and saying something along the lines of ”oh, you’re instantiating objects in a loop, that’s obviously going to be slow”. Like, what? If I can do this performantly in freakin PHP, how can Java, the flagship of OOP, not have fast instantiation of objects? I’m still shaking my head thinking about it.
Your tutor misdiagnosed the issue. These allocations in a tight loop would have used bump allocation on Java 6 in 2010, and the young generation would have used a copy collector, which would have freed those objects more cheaply than any unspecialized malloc/free. It would have beaten the pants off of PHP's reference counting GC.
I remember now what the problem was. I was instantiating a new ArrayList in a loop. The solution to the performance issue was to use a Vector instead. I was used to just writing PHP arrays when I wanted a list of something, and since they’re dynamically sized I thought the analogue in Java was ArrayList, which is also dynamically sized. But somehow that was extremely unperformant in Java.
Did you actually benchmark that task against similarly-architected PHP code?