diff options
author | Thomas Haller <thaller@redhat.com> | 2016-02-23 23:54:43 +0100 |
---|---|---|
committer | Thomas Haller <thaller@redhat.com> | 2016-02-24 11:24:13 +0100 |
commit | b913e1d641e98c99f27936d76828998ae5534fbb (patch) | |
tree | ca9fd49dba2514fffe76dec4e5b3f737dcf9ddfe | |
parent | f41aebf8973a70a0e0f44d93c52ccecee5c1f25e (diff) |
platform: optimize sysctl_set() to use stack allocated buffer
The value written to sysctl is usually a short string. It makes sense
to optimize for this case and avoid allocating a temporary string
on the heap.
An alternative would be to use writev(), which effectively does the same
and also creates a temporary buffer (preferably stack allocated).
https://mail.gnome.org/archives/networkmanager-list/2016-February/msg00070.html
-rw-r--r-- | src/platform/nm-linux-platform.c | 16 |
1 files changed, 12 insertions, 4 deletions
diff --git a/src/platform/nm-linux-platform.c b/src/platform/nm-linux-platform.c index 1ebffd0007..a1504d1993 100644 --- a/src/platform/nm-linux-platform.c +++ b/src/platform/nm-linux-platform.c @@ -2452,8 +2452,11 @@ _log_dbg_sysctl_set_impl (NMPlatform *platform, const char *path, const char *va static gboolean sysctl_set (NMPlatform *platform, const char *path, const char *value) { - int fd, len, nwrote, tries; + int fd, tries; + gssize nwrote; + gsize len; char *actual; + gs_free char *actual_free = NULL; g_return_val_if_fail (path != NULL, FALSE); g_return_val_if_fail (value != NULL, FALSE); @@ -2483,10 +2486,16 @@ sysctl_set (NMPlatform *platform, const char *path, const char *value) * sysctl support partial writes so the LF must be added to the string we're * about to write. */ - actual = g_strdup_printf ("%s\n", value); + len = strlen (value) + 1; + if (len > 512) + actual = actual_free = g_malloc (len + 1); + else + actual = g_alloca (len + 1); + memcpy (actual, value, len - 1); + actual[len - 1] = '\n'; + actual[len] = '\0'; /* Try to write the entire value three times if a partial write occurs */ - len = strlen (actual); for (tries = 0, nwrote = 0; tries < 3 && nwrote != len; tries++) { nwrote = write (fd, actual, len); if (nwrote == -1) { @@ -2505,7 +2514,6 @@ sysctl_set (NMPlatform *platform, const char *path, const char *value) path, value); } - g_free (actual); close (fd); return (nwrote == len); } |