So after my understandings, bytes and strings are basically doing the same just in different formats and using bytes is cheaper -leading to my question, should I then only use string for data that is longer than 32 bytes and specify byte type for anything below?
2 Answers
According to Solidity documentation:
As a rule of thumb, use bytes for arbitrary-length raw byte data and string for arbitrary-length string (UTF-8) data. If you can limit the length to a certain number of bytes, always use one of bytes1 to bytes32 because they are much cheaper.
Variables of type bytes and string are special arrays. A bytes is similar to byte[], but it is packed tightly in calldata. string is equal to bytes but does not allow length or index access (for now).
So yes, whenever you can, you should use bytes32 as opposed to string, as long as you are certain such data won't be longer than 32 characters.
-
Why did someone downvote the answer, sounds correct to me, can the downvoter please elaborate?– 6egicOct 12, 2017 at 12:46
Just to add to the reasons given here, string
can't be passed between contracts, so I incline to forcing clients to pack/unpack bytes32
and use it in place of string wherever possible.
This doesn't work.
pragma solidity ^0.4.15;
contract Str {
event LogX(string thing);
function x(string something) public returns(string success) {
LogX(something);
return something;
}
}
contract Try {
Str s;
function Try(string that) {
s = new Str();
string set = s.x(that); // <== string can't be communicated between contracts
}
}
Hope it helps.
-
You have the same problem if you replace
string
withbytes
in your example. Maybe more helpful to focus on fixed vs variable-length variables. (The question itself is a little fuzzy on this point)– carverOct 17, 2017 at 21:32 -
Just for the sake of curiosity is it gave you some error in the compilation or some warning ? to pass
string
between contracts? Oct 18, 2017 at 1:35 -
Yes, the issue the variable-length string versus the fixed length bytes32. The compiler doesn't always tell you about the issue. In this case raises an issue for contract
Try
that tries to make an impossible invocation ofStr
, but it doesn't raise a problem forStr
itself, so you just need to know that variable-length interfaces are not accessible from other contracts. Oct 18, 2017 at 2:03