8
$\begingroup$

Many programming languages (such as Java) make strings immutable to mitigate many potential serious security threats.

Are there any major downsides or issues with a language having all strings immutable?

$\endgroup$
2
  • 2
    $\begingroup$ Is there a source on immutable strings mitigating security threats? Anyone with access to code can probably access memory addresses directly and modify the string. $\endgroup$
    – kouta-kun
    May 16, 2023 at 17:56
  • 1
    $\begingroup$ I really wouldn't know what kind of security immutable strings could protect against $\endgroup$
    – mousetail
    May 16, 2023 at 17:57

3 Answers 3

13
$\begingroup$

Performance

Immutability in general is bad for performance. If you concatenate many strings together in a loop, for example, the needless copying and the GC overhead (if any) will hurt performance. For this reason, many languages have a mutable string type, for example Java’s StringBuilder.

$\endgroup$
1
9
$\begingroup$

Security is better for mutable strings in some situations

When memory is freed it is not cleared. The string may stay in memory for a long time after you are done using it potentially exposing sensitive information to other processes that can snoop on your memory.

For that reason, some languages have the concept of a SecureString that is mutable so you can zero out the data when you are done using it to prevent other processes from reading it.

$\endgroup$
1
  • 4
    $\begingroup$ In Java, char arrays are preferred over strings for passwords for this very reason, even though Java’s strings are immutable. $\endgroup$
    – Seggan
    May 16, 2023 at 17:56
2
$\begingroup$

C FFI

The only "definite" downside I can think of is C-FFI. If you want to have C-interop, you may need to convert your language into C-style string (which is mutable) back and forth every time, or you try to use strings as char arrays in your language directly to avoid the conversion, which mostly defeats the purpose of having a dedicate string type.

$\endgroup$
2
  • $\begingroup$ I don't think this is related to C FFI in and of itself, since the question doesn't mention whether they would be null-terminated strings or length-prefixed. $\endgroup$
    – kouta-kun
    May 16, 2023 at 17:55
  • $\begingroup$ @kouta-kun I'm talking about immutable vs. mutable strings. $\endgroup$
    – ice1000
    May 16, 2023 at 17:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .