-3

What is the difference between these in Android / Java? Which is more efficient and what tool did you use to find the differences?

String text = input.getText().toString();

String text = String.valueOf(input.getText());

String text = input.getText() + "";

assuming input is not null...

EDIT: input.getText() returns an Editable.

Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
Nickmccomb
  • 1,467
  • 3
  • 19
  • 34

2 Answers2

3

Definitely toString().
It clearly states what you want, i.e. to get the String of the returned Editable.

getText() cannot return null, so the null safety of String.valueOf() is not needed, and String.valueOf() simply turns around and calls toString(), so why not just call it directly, since that is shorter?

input.getText() + "" is just lazy and obscure and generates bad code. Sure, JIT may eliminate it, but it's still a hack. (My opinion anyway)

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • That's a better answer. I've always used .toString() but we've been outsourcing and they are all using "" + input.getText() and i've been wondering if it's quicker. I found another post that said it's slower that way, so it seems like toString() is the most efficient and, in my view, elegant solution. – Nickmccomb Jun 24 '16 at 05:35
0

toString() is the best method to call. text+"" is the dirty way of coding.

Pronoy999
  • 645
  • 6
  • 25