Until today Gecko's support for string constants was quite poor. You could create a literal string or a named literal string on the stack and pass it to a method but any operation on the string ended up copying the string. In effect a literal string was a dependent string whose length was known at compile time (and also there is some magic for creating a wide Unicode constant).

Bug 514173 has landed, which makes use of the fact that code living in libxul can reasonably assume that string constants have infinite lifetime, meaning that any literal strings in libxul are shared rather than copied. The obvious case is assigning a string to an NS_LITERAL_(C)STRING, but this also affects AssignLiteral on an ns(A)CString. This sharing propagates, so for instance you can pass an NS_LITERAL_STRING to a setter that saves it in a member, then call the getter, and your returned string will still be pointing to the underlying string constant. (The buffer is copied if you try to mutate the string of course.)

This does not apply to AssignLiteral on an nsString, since that used to take a char (&)[] parameter. Instead, consider assigning an NS_LITERAL_STRING, or you can also use the new char16_t overload of AssignLiteral by wrapping your string constant in MOZ_UTF16().

Unlike dependent strings, string literals are also shared when you pass them through XPCStringConvert to the JS engine. (I wonder whether there's a way to detect them on the way out too. Currently XPCConvert only tries to use a dependent string if it can.)

There is one gotcha with this and that is that the type of NS_LITERAL_STRING, which has always been nsLiteral(C)String, used to be a typedef for nsDependent(C)String, but no longer is. Some people were relying on that by using const nsDependentCString& as a parameter type instead of, say, const nsACString&. Other consumers constructed an nsDependentString from an NS_LITERAL_STRING instead of using an NS_NAMED_LITERAL_STRING or just using the NS_LITERAL_STRING inline.

--
Warning: May contain traces of nuts.
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to