Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is g_slice really faster than malloc

Tags:

malloc

glib

The GLib docs recommend use of the GLib Slice Allocator over malloc:

"For newly written code it is recommended to use the new g_slice API instead of g_malloc() and friends, as long as objects are not resized during their lifetime and the object size used at allocation time is still available when freeing." -- http://developer.gnome.org/glib/unstable/glib-Memory-Slices.html

But in practise is g_slice significantly faster than Windows/Linux malloc(faster enough to warrant the extra trouble of handling sizes and GLib's preprocessor hacks like g_slice_new)? I'm planning to use GLib in my C++ program to handle INIish configuration (GKeyFile) and to get access to data structures not available in C++ like GHashTable, so the GLib dependency doesn't matter anyway.

like image 938
Sudarshan S Avatar asked Jan 19 '23 07:01

Sudarshan S


2 Answers

Faster enough to be worth it sort of depends on your app. But they should be faster.

There is another issue besides speed, which is memory fragmentation and per-block overhead. GSlice leaves malloc to deal with large or variable-size allocations while handling small known-size objects more space-efficiently.

like image 105
Havoc P Avatar answered Jan 21 '23 20:01

Havoc P


Slice API heavily borrows from research conducted by Sun Microsystems in 1980s and it was called slab allocation back then. I could not find original research paper but here is a wikipedia page about it or you can just google for "slab allocation".

Essentially it eliminates expensive allocation/deallocation operations by facilitating reuse of memory blocks. It also reduces or eliminates memory fragmentation. So it is not all about speed, even though it should improve it as well.

If you should used or not - it depends... Look at Havoc's answer - he summarized it pretty well.

Update 1:

Note, that modern Linux kernels include SLAB allocator as one of the option and it is often the default. So, the difference between g_slice() and malloc() may be unnoticeable in that case. However, purpose of glib is cross-platform compatibility, so using slice API may somewhat guarantee consistent performance across different platforms.

Update 2:

As it was pointed by a commenter my first update is incorrect. SLAB allocation is used by kernel to allocate memory to processes but malloc() uses an unrelated mechanism, so claim that malloc() is equivalent to g_slice() on Linux is invalid. Also see this answer for more details.

like image 45
dtoux Avatar answered Jan 21 '23 20:01

dtoux