6

Is array access in Java expensive compared to C++?

 2 years ago
source link: https://www.programmerinterview.com/general-miscellaneous/is-array-access-in-java-expensive-compared-to-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Is array access in Java expensive compared to C++? If so, what is the reason?

Yes, array access in Java is more expensive than array access in C and C++.

Bounds checking in Java slows down array access

The reason that accessing an element in an array in Java is expensive is because of the fact that Java performs bounds checking every time an element in an array is accessed. Bounds checking is where an access to an array index is checked against the size of the array – and an exception is thrown if that array index is out of bounds, and larger than the size of the array. So, if an array has a size of 30, but you try to access the element at index 45, then Java will throw an exception because of the bounds checking feature. And because Java checks the size of the array before accessing the element at index 45, that is an extra operation that is more expensive compared to C and C++, which do not perform bounds checking.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK